gpt4 book ai didi

php - 如何读/写 64 位无符号小端整数?

转载 作者:搜寻专家 更新时间:2023-10-31 21:33:53 25 4
gpt4 key购买 nike

pack不支持它们,那么如何读写 64 位无符号小端编码整数?

最佳答案

您可以将 64 位数字视为 8 字节二进制数据的不透明 block ,并使用通常的字符串操作函数来处理它们(即 substr 和最重要的点运算符)。

无论何时(如果)您需要对它们执行算术运算,您都可以使用几个包装函数以十六进制表示形式对该 block 进行编码/解码(在我的实现中,我将此中间类型称为 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");
}

关于php - 如何读/写 64 位无符号小端整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24540978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com