sdaau sdaau - 1 year ago 89
Perl Question

Perl pack/unpack and length of binary string

Consider this short example:

$a = pack("d",255);
print length($a)."\n";
# Prints 8

$aa = pack("ddddd", 255,123,0,45,123);
print length($aa)."\n";
# Prints 40

@unparray = unpack("d "x5, $aa);
print scalar(@unparray)."\n";
# Prints 5

print length($unparray[0])."\n"
# Prints 3

printf "%d\n", $unparray[0] '
# Prints 255

# As a one-liner:
# perl -e '$a = pack("d",255); print length($a)."\n"; $aa = pack("dd", 255,123,0,45,123); print length($aa)."\n"; @unparray = unpack("d "x5, $aa); print scalar(@unparray)."\n"; print length($unparray[0])."\n"; printf "%d\n", $unparray[0] '

Now, I'd expect a double-precision float to be eight bytes, so the first
is correct. But why is the length after the unpack (
) reporting 3 - when I'm trying to go back the exact same way (double-precision, i.e. eight bytes) - and the value of the item (255) is correctly preserved?

Answer Source

By unpacking what you packed, you've gotten back the original values, and the first value is 255. The stringification of 255 is "255", which is 3 characters long, and that's what length tells you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download