<?php
// 22位压缩后的 UUID解码配置
$BASE64_KEYS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
$values = array_fill(0, 123, 64); // max char code in base64Keys
for ($i = 0; $i < 64; ++$i) {
$charCode = ord($BASE64_KEYS[$i]);
$values[$charCode] = $i;
}
// 23位压缩后的 UUID解码配置
$Base64KeyChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
$AsciiTo64 = array_fill(0, 128, 0);
for ($i = 0; $i < 64; ++$i) {
$charCode = ord($Base64KeyChars[$i]);
$AsciiTo64[$charCode] = $i;
}
// 其他配置
$BASE64_VALUES = $values;
$HexChars = str_split('0123456789abcdef');
$_t = array('', '', '', '');
// 修正 $UuidTemplate 的初始化
$UuidTemplate = array_merge($_t, $_t, array('-'), $_t, array('-'), $_t, array('-'), $_t, array('-'), $_t, $_t, $_t);
// 生成 $Indices
$Indices = array();
foreach ($UuidTemplate as $key => $value) {
if ($value !== '-') {
$Indices[] = $key;
}
}
/**
* 22位压缩后的 UUID解码
* @param string $base64 压缩后的 UUID 字符串
* @return string 解码后的标准 UUID 字符串
*/
function decodeUuid($base64) {
global $BASE64_VALUES, $Indices, $HexChars;
$strs = explode('@', $base64);
$uuid = $strs[0];
if (strlen($uuid) !== 22) {
return decompressUuid($uuid);
}
$result = array_fill(0, 36, '-');
$result[0] = $base64[0];
$result[1] = $base64[1];
$index = 2;
for ($i = 2; $i < 22; $i += 2) {
$lhs = $BASE64_VALUES[ord($base64[$i])];
$rhs = $BASE64_VALUES[ord($base64[$i + 1])];
$result[$Indices[$index++]] = $HexChars[($lhs >> 2) & 0xF];
$result[$Indices[$index++]] = $HexChars[(((3 & $lhs) << 2) | ($rhs >> 4)) & 0xF];
$result[$Indices[$index++]] = $HexChars[$rhs & 0xF];
}
return implode('', $result);
}
/**
* 23位压缩后的 UUID解码
* @param string $uuid 压缩后的 UUID 字符串
* @return string 解码后的标准 UUID 字符串
*/
function decompressUuid($uuid) {
global $AsciiTo64, $HexChars;
// 检查输入的 uuid 长度是否符合要求
if (strlen($uuid) < 23) {
error_log('Invalid UUID length. Expected at least 23 characters.');
return '';
}
// 存储解码后的十六进制字符
$decodedHexChars = array();
// 从第 5 个字符开始,每 2 个字符一组进行解码
for ($index = 5; $index < 23; $index += 2) {
$firstCharValue = $AsciiTo64[ord($uuid[$index])];
$secondCharValue = $AsciiTo64[ord($uuid[$index + 1])];
// 解码逻辑
$decodedHexChars[] = dechex($firstCharValue >> 2);
$decodedHexChars[] = dechex(((3 & $firstCharValue) << 2) | ($secondCharValue >> 4));
$decodedHexChars[] = dechex(15 & $secondCharValue);
}
// 拼接解码后的 uuid
$decodedUuid = substr($uuid, 0, 5) . implode('', $decodedHexChars);
// 格式化 uuid 为标准格式
return implode('-', array(
substr($decodedUuid, 0, 8),
substr($decodedUuid, 8, 4),
substr($decodedUuid, 12, 4),
substr($decodedUuid, 16, 4),
substr($decodedUuid, 20)
));
}
// 测试
$compressedUuid22 = 'example22char@';
$compressedUuid23 = 'example23char';
echo decodeUuid($compressedUuid22) . "\n";
echo decompressUuid($compressedUuid23) . "\n";
?>
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END







暂无评论内容