这是一个将任意大小的整数值打包成 N 位的函数:
function encode_int($in, $pad_to_bits=64, $little_endian=true) {
$in = decbin($in);
$in = str_pad($in, $pad_to_bits, '0', STR_PAD_LEFT);
$out = '';
for ($i = 0, $len = strlen($in); $i < $len; $i += 8) {
$out .= chr(bindec(substr($in,$i,8)));
}
if($little_endian) $out = strrev($out);
return $out;
}
这是一个解码打包整数的函数:
function decode_int(&$data, $bits=false) {
if ($bits === false) $bits = strlen($data) * 8;
if($bits <= 0 ) return false;
switch($bits) {
case 8:
$return = unpack('C',$data);
$return = $return[1];
break;
case 16:
$return = unpack('v',$data);
$return = $return[1];
break;
case 24:
$return = unpack('ca/ab/cc', $data);
$return = $return['a'] + ($return['b'] << 8) + ($return['c'] << 16);
break;
case 32:
$return = unpack('V', $data);
$return = $return[1];
break;
case 48:
$return = unpack('va/vb/vc', $data);
$return = $return['a'] + ($return['b'] << 16) + ($return['c'] << 32);
break;
case 64:
$return = unpack('Va/Vb', $data);
$return = $return['a'] + ($return['b'] << 32);
break;
}
return $return;
}