Can someone explain to me the pack() function in PHP?

送分小仙女□ 提交于 2019-12-29 04:27:10

问题


I would like to know more about the pack() function in PHP: https://secure.php.net/manual/en/function.pack.php

I know it packs data into binary, but I'm not sure what all those v V n N c C mean and I was wondering if someone could be so kind as to give me a practical demonstration when to use which formats?

The online documentation, for a change, lacks of information, in my opinion.


回答1:


Those represent how you want the data you are packing to be represented in binary format:

so

$bin = pack("v", 1); => 0000000000000001 (16bit)

where

$bin = pack("V", 1) => 00000000000000000000000000000001 (32 bit)

It tells pack how you want the data represented in the binary data. The code below will demonstrate this. Note that you can unpack with a different format from what you packed the data as.

<?php

$bin = pack("S", 65535);
$ray = unpack("S", $bin);
echo "UNSIGNED SHORT VAL = ", $ray[1], "\n";

$bin = pack("S", 65536);
$ray = unpack("S", $bin);
echo "OVERFLOW USHORT VAL = ", $ray[1], "\n";

$bin = pack("V", 65536);
$ray = unpack("V", $bin);
echo "SAME AS ABOVE BUT WITH ULONG VAL = ", $ray[1], "\n";
?>



回答2:


As noted in the php documentation for pack, the function is borrowed from Perl's pack function.

Take a look at Perl's documentation for pack, specifically the examples section at the very bottom of the page. PHP's pack does not implement all the formats, but Perl's documentation for the function does a better job of providing examples and explaining each format.



来源:https://stackoverflow.com/questions/987854/can-someone-explain-to-me-the-pack-function-in-php

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