直接通过字符集映射表实现自定义进制转换,核心是建立“字符-数值”与“数值-字符”的双向索引,利用模除和整除运算完成进位处理。

理解非标字符集的映射原理
Base62等非标进制不同于标准的二、八、十、十六进制,其基数由自定义字符集长度决定。例如 Base62 使用 A-Z、a-z、0-9 共 62 个字符作为符号位。

转换的本质是将目标进制的字符串视为一个多项式系数序列。对于输入字符串 S,其对应的十进制数值 N 可通过遍历每个字符并累加得到:
N = S[0] * B^(L-1) + S[1] * B^(L-2) + ... + S[L-1] * B^0,其中 B 为基数(字符集长度),L 为字符串长度。
反之,将十进制数 N 转换为目标进制字符串时,采用短除法:不断对基数 B 取余,余数对应字符集中的索引,商继续参与下一轮除法,直到商为 0。将每次得到的字符逆序排列即为结果。
实现双向转换的核心函数
在 PHP 中,由于整数精度限制,大数转换需借助 BCMath 或 GMP 扩展,但常规业务场景下可使用标准整数类型配合自定义逻辑。

<?php
class CustomBaseConverter
{
private string $charset;
private int $base;
private array $charToValue;
private array $valueToChar;
public function __construct(string $charset)
{
// 去重并验证字符集
$uniqueChars = array_unique(str_split($charset));
if (count($uniqueChars) !== strlen($charset)) {
throw new InvalidArgumentException("Charset contains duplicate characters.");
}
$this->charset = $charset;
$this->base = strlen($charset);
// 构建双向映射表
$this->charToValue = [];
$this->valueToChar = [];
for ($i = 0; $i < $this->base; $i++) {
$char = $charset[$i];
$this->charToValue[$char] = $i;
$this->valueToChar[$i] = $char;
}
}
/**
* 将任意进制字符串转换为十进制整数
*/
public function toDecimal(string $input): int
{
$decimal = 0;
$len = strlen($input);
for ($i = 0; $i < $len; $i++) {
$char = $input[$i];
if (!isset($this->charToValue[$char])) {
throw new InvalidArgumentException("Invalid character: $char");
}
$decimal = $decimal * $this->base + $this->charToValue[$char];
}
return $decimal;
}
/**
* 将十进制整数转换为自定义进制字符串
*/
public function fromDecimal(int $decimal): string
{
if ($decimal === 0) {
return $this->valueToChar[0];
}
$result = '';
$isNegative = false;
if ($decimal < 0) {
$isNegative = true;
$decimal = -$decimal;
}
while ($decimal > 0) {
$remainder = $decimal % $this->base;
$result = $this->valueToChar[$remainder] . $result;
$decimal = intdiv($decimal, $this->base);
}
return $isNegative ? '-' . $result : $result;
}
/**
* 直接在两个自定义进制间转换
*/
public function convert(string $input, string $targetCharset):
self
{
// 临时实例用于目标字符集转换
$tempConverter = new self($targetCharset);
$decimal = $this->toDecimal($input);
return $tempConverter->fromDecimal($decimal);
}
}
// 示例用法
$base62Charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$converter = new CustomBaseConverter($base62Charset);
// Base62 -> Decimal
$decimalValue = $converter->toDecimal('A1z');
echo "Base62 'A1z' to Decimal: {$decimalValue}\n";
// Decimal -> Base62
$base62String = $converter->fromDecimal(123456789);
echo "Decimal 123456789 to Base62: {$base62String}\n";
// Cross-base conversion example (simulated with different charset)
$customCharset = '0123456789ABCDEF'; // Hex-like
$hexConverter = new CustomBaseConverter($customCharset);
$result = $hexConverter->convert('A1z', $base62Charset); // This will fail due to invalid char in source
try {
$result = $hexConverter->convert('FF', $base62Charset);
echo "Hex 'FF' to Base62: {$result}\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
运行上述代码,控制台将输出 Base62 字符串到十进制数的映射值,以及十进制数反向转换后的 Base62 表示。例如 'A1z' 会被正确解析为特定整数,而 123456789 会转换为一串 Base62 字符。若尝试转换包含非法字符的字符串,程序将抛出异常,便于排查输入错误。注意,跨进制转换时需确保源字符串仅包含源字符集内的字符,否则 toDecimal 方法会拦截无效输入。
以下代码实现了基于指定字符集的互转功能。关键步骤包括构建查找表以优化性能,以及处理空值和非法字符校验。
处理前导零与负数边界情况
当输入包含前导零或需要支持负数时,标准算法需额外分支处理,否则会导致结果丢失精度或格式错误。
在实际应用中,若原始数据包含前导零(如 ID 编码),直接转为数值会丢失这些零。因此,建议在转换前先分离符号位和前导零部分,仅对有效数值部分进行进制转换,接着拼接回前缀。PHP 的 bcdiv 等函数默认向下取整,需注意负数取模时的符号一致性,通常建议统一转为正数计算后再恢复符号。