5

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);

2 Answers 2

7

$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

1
  • It was in fact an unsigned long, so 'L' was what I need, but close enough!
    – bukzor
    Commented Dec 15, 2010 at 22:27
3

Look at the unpack function

1
  • True, but part of SO is encouraging and helping people to find their own answers. Commented Dec 16, 2010 at 23:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.