我想使用 PHP 转换以 36 为基数的数字。函数 base_convert
不起作用,因为我想转换大数字:如果我再次将其从基数 36 转换为十进制,我不会得到我的初始数字。
我尝试了多个网站上给出的一些功能,但我从未得到相同的结果。此外,这两个网站(在Javascript中(给出相同的结果:
- http://www.unitconversion.org/numbers/base-10-to-base-36-conversion.html
- http://www.translatorscafe.com/cafe/units-converter/numbers/calculator/decimal-to-base-36/
例如,1010701001118000000000000000
必须转换为 3IZS0ZE1RQ68W8SSW4
。
以下是我尝试过的功能(但不起作用(:
- http://www.php.net/manual/fr/function.base-convert.php#34510
- http://www.php.net/manual/fr/function.base-convert.php#106546
- http://www.tonymarston.net/php-mysql/showsource.php?file=converter.php
- http://www.geoffray.be/blog/php/convertir-des-nombres-en-base-62
这里有两个简单的函数,使用维基百科上的算法,同时使用 bcmath 来正确计算,即使是非常大的数字:
function fromDecimalToBase($in, $to) {
$in = (string) $in;
$out = '';
for ($i = strlen($in) - 1; $i >= 0; $i--) {
$out = base_convert(bcmod($in, $to), 10, $to) . $out;
$in = bcdiv($in, $to);
}
return preg_replace('/^0+/', '', $out);
}
function fromBaseToDecimal($in, $from) {
$in = (string) $in;
$out = '';
for ($i = 0, $l = strlen($in); $i < $l; $i++) {
$x = base_convert(substr($in, $i, 1), $from, 10);
$out = bcadd(bcmul($out, $from), $x);
}
return preg_replace('/^0+/', '', $out);
}
但是,我对您提供的号码感到3izs0ze1rq66tifrpc
- 也许您的转换是错误的?
http://www.pgregg.com/projects/php/base_conversion/base_conversion.php
本页介绍如何在不同基数之间转换任意长度的数字。我尝试了你的例子,看起来它在两个方向上都有效。用 PHP 编写的源代码可用。