http://www.perlmonks.org?node_id=198085

notfred has asked for the wisdom of the Perl Monks concerning the following question:

I have 4 bytes of data read in from a binary file. I need to treat this data as an 'int' in C, and get it's binary value. Perl wants to treat it as four characters, however. Is there any simple way to treat it as an integer, or convert it to an integer? Right now I have the painfully long:
sub BinWordToDec { # There's GOT to be a better way to do this conversion.... # Converts a 32 bit binary word to a decimal integer. my $val = $_[0]; my $temp = "0b$val"; print "temp: $temp\n"; unless (length $val == 4) {return -1} my $bit1 = ord (substr $val,0,1); my $bit2 = ord (substr $val,1,1); my $bit3 = ord (substr $val,2,1); my $bit4 = ord (substr $val,3,1); $bit1 = unpack("B*", pack("N", $bit1)); $bit2 = unpack("B*", pack("N", $bit2)); $bit3 = unpack("B*", pack("N", $bit3)); $bit4 = unpack("B*", pack("N", $bit4)); my $dec = substr("0" x 8 . $bit1, -8).substr("0" x 8 . $bit2, -8). substr("0" x 8 . $bit3, -8).substr("0" x 8 . $bit4, -8); my $int = unpack("N", pack("B32", $dec)); $dec = sprintf("%d", $int); print "Decimal: \n", $dec, "\n"; return $dec; }
Thanks

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I convert a 32 bit unsigned integer to it's decimal value.
by BrowserUk (Patriarch) on Sep 15, 2002 at 22:13 UTC
    Given you are already using unpack, why not let it do the whole job?

    perl> print unpack( 'N', chr(255).chr(255).chr(255).chr(255) ) 4294967295

    The only caveat to this (or blakm's solution above) is that if the data is sourced from a system other than your own, the byte-order my be different (big-endian .v. little-endian ot vice versa) in which case you would need to use an unpack template of 'V'. The difference is demonstrated by

    perl> print unpack( 'N', chr(255).chr(127).chr(64).chr(32) ) 4286529568 perl> print unpack( 'V', chr(255).chr(127).chr(64).chr(32) ) 541097983
    If the source is a foriegn system, and you are unsure of the byte ordering, you'll need a sample known value and try both to make your determination of which of 'N' or 'V' to use.
Re: How do I convert a 32 bit unsigned integer to it's decimal value.
by blakem (Monsignor) on Sep 15, 2002 at 21:34 UTC
Re: How do I convert a 32 bit unsigned integer to it's decimal value.
by Juerd (Abbot) on Sep 15, 2002 at 22:12 UTC
Re: How do I convert a 32 bit unsigned integer to it's decimal value.
by jmcnamara (Monsignor) on Sep 15, 2002 at 22:33 UTC
    $int = unpack 'N', $str;

    You could also use unpack 'V' but based on your code 'N' is what you need.

Re: How do I convert a 32 bit unsigned integer to its decimal value?
by notfred (Initiate) on Sep 16, 2002 at 02:08 UTC