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:
Thankssub 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; }
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 | |
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 | |
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 |
Back to
Seekers of Perl Wisdom