pack
不支持它们,那么如何读写64位无符号小端编码整数呢?
答案 0 :(得分:1)
您可以将64位数视为8字节二进制数据的不透明块,并使用通常的字符串操作函数来处理它们(例如substr
和点运算符)。
每当(以及如果)你需要对它们执行算术运算时,你可以使用几个包装器函数以十六进制表示形式编码/解码该块(在我的实现中我称之为中间类型hex64
)和使用您喜欢的外部库来完成实际工作:
<?php
/* Save as test.php */
function chunk_to_hex64($chunk) {
assert(strlen($chunk) == 8);
return strrev(bin2hex($chunk));
}
function hex64_to_chunk($hex64) {
assert(strlen($hex64) == 16);
return strrev(pack('h*', $hex64));
}
// Test code:
function to_hex64($number) {
$hex64 = base_convert($number, 10, 16);
// Ensure the hex64 is left padded with '0'
return str_pad($hex64, 16, '0');
}
for ($number = 0.0; $number < 18446744073709551615.0; $number += 2932031007403.0) {
$hex64 = to_hex64($number);
$hex64_reencoded = chunk_to_hex64(hex64_to_chunk($hex64));
assert($hex64_reencoded == $hex64, "Result is $hex64_reencoded, expected $hex64");
}
$data = file_get_contents('test.php');
// Skip the last element because it is not 8 bytes
$chunks = array_slice(str_split($data, 8), 0, -1);
foreach ($chunks as $chunk) {
$hex64 = to_hex64($number);
$chunk_reencoded = hex64_to_chunk(chunk_to_hex64($chunk));
assert($chunk_reencoded == $chunk, "Result is $chunk_reencoded, expected $chunk");
}
答案 1 :(得分:0)
我写了一个helper class来打包/解包64位无符号整数。
相关位只有两行:
$ints = unpack("@$offset/Vlo/Vhi", $data);
$sum = Math::add($ints['lo'], Math::mul($ints['hi'], '4294967296'));
(Math::*
是bcmath的简单包装器)
包装:
$out .= pack('VV', (int)bcmod($args[$idx],'4294967296'), (int)bcdiv($args[$idx],'4294967296'));
它将64位整数分成两个32位整数,64位PHP应该支持: - )