in reply to Mysteries of unpack("a", ...)
Does this look right for the value in your example?
$n = unpack 'N', pack 'B32', '01000010001111000000000000000000';; ( $s, $c, $e ) = ( $n & 0x8000_0000, (( $n >> 24 ) & 0x7f) - 64, (($n & 0x00ffffff) / 0xffffff) * 16 );; print $s, $c, $e;; 0 2 3.75000022351743 $num = ($s? -1 : 1 ) * $e * 10**$c;; print $num;;
375.000022351743
If so, then the following modification of your subroutine may be what you need:
sub parse_E ($) { my $data = shift; ## The data comes in as a 4-byte string so... $data = unpack 'N', $data; ## We need to treat it as an unsigned i +nteger ## in order to do bitwise math on it my ($sign, $characteristic, $fraction); $sign = ($data & 0x80000000) ? -1 : 1; $characteristic = (($data >> 24) & 0x7f) - 64; $fraction = (($data & 0x00ffffff) / 0xffffff) * 16; ## Not the fraction raised to the power of the characteristic ## my $num = $sign * $fraction ** $characteristic; ## But rather, the fraction * 10 to the power of the characteristic my $num = $sign * $fraction * 10 ** $characteristic; printf("DEBUG: parse_E(%32s)\n\tsign: %d charisteristic: %d ". "fraction: %f = %f\n", unpack ("B32", $data), $sign, $characteristic, $fraction, $num); printf("DEBUG: unpacked characteristic %s\n", unpack ("B7", ($data >> 24) & 0x7f)); printf("DEBUG: unpacked fraction %7s%s\n", " ", unpack ("B24", $data & 0x00ffffff)); return $num; }
Some inferences drawn from here, though it could definitely be more clearly stated.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Mysteries of unpack("a", ...)
by pspinler (Novice) on Jan 03, 2009 at 06:26 UTC | |
by gone2015 (Deacon) on Jan 04, 2009 at 01:49 UTC |