Perl pack/unpack and length of binary string

2019-04-13 13:25发布

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 length($a) is correct. But why is the length after the unpack (length($unparray[0])) 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?

1条回答
别忘想泡老子
2楼-- · 2019-04-13 14:04

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.

查看更多
登录 后发表回答