Perl pack/unpack and length of binary string

天涯浪子 提交于 2020-01-13 05:09:09

问题


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:


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.



来源:https://stackoverflow.com/questions/8320880/perl-pack-unpack-and-length-of-binary-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!