Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, how can I convert a binary string to an integer?

I have a four-byte string read from a binary file, which is supposed to represent an integer. How do I dervive the integer?

Example:

my $s = '\xa8e2~';
my $i = stoi($s);
printf "%X", $i;  #gives "0x7e3265a8"

The solution in C is simply:

fread(&i,4,1,fp);
like image 762
bukzor Avatar asked Jan 21 '23 21:01

bukzor


2 Answers

$i = unpack("s", $s) may work, but it depends on signed/unsigned and byte ordering so you'll probably end up here: http://perldoc.perl.org/perlpacktut.html#Integers

like image 169
Brad Mace Avatar answered Jan 28 '23 16:01

Brad Mace


Look at the unpack function

like image 29
Jim Garrison Avatar answered Jan 28 '23 14:01

Jim Garrison