示例:从 php v4 生成的 Uuid :
8bc278cb-2fb6-413b-add6-8ba39bf830e8
我想将其转换为两个 64 位整数。
我尝试过使用hexdecphp 但它的返回值是数字。我想要整数数据类型。
有趣的是 :
我尝试将 hexdec 与上述 uuid 一起使用,并将此输出用于 dechex。有些怎么样,没有得到相同的值?
任何对此的见解将不胜感激。
UUID 是一种 128 位数据类型。除去6个保留位,其中还有122个数据位。使得无法将任何 UUID 完全转换为 64 位整数。您至少需要将其存储为 2 个 64 位数字或 4 个 32 位数字。
您可以将 UUID 解压为二进制,然后将其解压为 4 个 32 位无符号字符:
function uuidToHex($uuid) {
return str_replace('-', '', $uuid);
}
function hexToUuid($hex) {
$regex = '/^([\da-f]{8})([\da-f]{4})([\da-f]{4})([\da-f]{4})([\da-f]{12})$/';
return preg_match($regex, $hex, $matches) ?
"{$matches[1]}-{$matches[2]}-{$matches[3]}-{$matches[4]}-{$matches[5]}" :
FALSE;
}
function hexToIntegers($hex) {
$bin = pack('h*', $hex);
return unpack('L*', $bin);
}
function integersToHex($integers) {
$args = $integers; $args[0] = 'L*'; ksort($args);
$bin = call_user_func_array('pack', $args);
$results = unpack('h*', $bin);
return $results[1];
}
$uuid = '1968ec4a-2a73-11df-9aca-00012e27a270';
var_dump($uuid);
$integers = hexToIntegers(uuidToHex('1968ec4a-2a73-11df-9aca-00012e27a270'));
var_dump($integers);
$uuid = hexToUuid(integersToHex($integers));
var_dump($uuid);
Run Code Online (Sandbox Code Playgroud)
它会返回
string(36) "1968ec4a-2a73-11df-9aca-00012e27a270"
array(4) {
[1]=>
int(2764998289)
[2]=>
int(4245764002)
[3]=>
int(268479657)
[4]=>
int(120222434)
}
string(36) "1968ec4a-2a73-11df-9aca-00012e27a270"
Run Code Online (Sandbox Code Playgroud)
$integers是一个由 4 个 32 位数字组成的数组,表示十六进制。