pack用于将数据打包成二进制字符串

unpack用于对二进制字符串解包

一些案列

<?php

//打包为NUL填充的、3个字节长度的二进制字符串(utf8里1个汉字占3个字节)
$binstr = pack("a3", '中');
echo "binary strlen:" . strlen($binstr) . PHP_EOL;
echo "binary str:" . $binstr . PHP_EOL;
echo "bin2hex:" . bin2hex($binstr) . PHP_EOL;
echo "hex to str:" . chr(0xe4) . chr(0xb8) . chr(0xad) . PHP_EOL;
echo "raw binary:" . $binstr[0] . $binstr[1] . $binstr[2] . PHP_EOL;

//输出结果为
//binary strlen:3
//binary str:中
//bin2hex:e4b8ad => 汉字的utf8编码
//hex to str:中
//raw binary:中

Post Navigation