For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > October 2006 > Convert character string to integer









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Convert character string to integer
d99alu@efd.lth.se

2006-10-24, 3:56 am

Hi!

I'm trying to parse a binary file with some16-bit data and some 32-bit
data fields. These values I'd like to print in a nice decimal format.
How can I print this as a decimal number, and not as a character
string? Thanks a lot for your help. The output right now is typically:

Value =3D ?^
NoOfParams =3D S
Value =3D 'z??
NoOfParams =3D =BCG

The interesting part of the code looks like:
open(FILE, $filename) or die "Can't open $filename: $!\n";
binmode FILE;
# 16 bit
$len =3D 2;
read FILE, $u16var , $len;
print "NoOfParams =3D ".$u16var."\n"; # First try
#sprintf("NoOfParams =3D %d", $u16var); #Second try...
#32 bit
$len =3D 4;
read FILE, $u32var , $len;
print "Value =3D ".$u32var."\n";


The entire code looks like this:

#!/usr/bin/perl use File::Find;
use Cwd; my $dir =3D cwd();
my @all;
my $u16var;
my $u32var;
my $i;
my $len;

# Issue the find command passing two arguments
find(\&foreachfile, $dir); sub foreachfile() {
my $filename =3D $File::Find::name;
if ($filename =3D~ m/sba.*data\.dat/)
{
open(FILE, $filename) or die "Can't open $filename: $!\n";
binmode FILE;
open(FILE_OUT, ">".$filename."\.txt") or die "Can't open
$filename\.tmp: $!\n";
@stat =3D stat FILE;
while (!eof(FILE))
{
$len =3D 2;
read FILE, $u16var , $len;
print "NoOfParams =3D ".$u16var."\n";
$len =3D 4;
read FILE, $u32var , $len;
print "Value =3D ".$u32var."\n";
}
close(FILE);
close(FILE_OUT);
}
}=20

Best regards,
Andreas Lundgren (sw)

nobull67@gmail.com

2006-10-24, 3:56 am


d99alu@efd.lth.se wrote:
>
> I'm trying to parse a binary file with some16-bit data and some 32-bit
> data fields. These values I'd like to print in a nice decimal format.
> How can I print this as a decimal number, and not as a character
> string?


perldoc -f unpack

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com