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.