【问题标题】:Convert Alphanumeric (Base36) to int (Base10) and Viceversa将字母数字 (Base36) 转换为 int (Base 10),反之亦然
【发布时间】:2022-01-07 14:02:50
【问题描述】:

我有这个字符串“AUB9789LJLKA89”。我需要将其转换为 int,稍后我需要能够将其转换回字符串。

为了做到这一点,我在 PHP“base_convert”中找到,但是当我将“AUB9789LJLKA89”转换为 Base10 时,我得到了数字:1849450200354407248260,如果我将该数字转换回 Base36,我得到“AUB9789LJLKWCC”。与“AUB9789LJLKA89”大不相同。

base_convert("AUB9789LJLKA89", 36, 10); //I get 1849450200354407248260
base_convert(1849450200354407248260, 10, 36); //I get AUB9789LJLKWCC

我该如何解决这个问题?或者我可以使用哪种其他方式将字母数字转换为 int 方式并返回。

【问题讨论】:

  • 可能是因为 PHP 文档中的警告:php.net/manual/en/function.base-convert.php (base_convert() 由于与内部“double”或“float”类型相关的属性,可能会丢失大数的精度使用)。
  • 另外,我认为您可能正在处理比 PHP 可以处理的更大的数字。 1849450200354407248260 比 PHP_INT_MAX 的 9223372036854775807 长 3 位。你可能需要使用类似 GMP 的东西,php.net/manual/en/ref.gmp.php,第一个例子是转换碱基。

标签: php converters base


【解决方案1】:

我在php doc 页面找到了这个用于转换贡献者编写的碱基的功能,试试看它是否能给你想要的结果。

function convBase($numberInput, $fromBaseInput, $toBaseInput)
{
    if ($fromBaseInput == $toBaseInput) {
        return $numberInput;
    }

    $fromBase = str_split($fromBaseInput, 1);
    $toBase = str_split($toBaseInput, 1);
    $number = str_split($numberInput, 1);
    $fromLen = strlen($fromBaseInput);
    $toLen = strlen($toBaseInput);
    $numberLen = strlen($numberInput);
    $retval = '';
    if ($toBaseInput == '0123456789') {
        $retval = 0;
        for ($i = 1; $i <= $numberLen; $i++) {
            $retval = bcadd($retval, bcmul(array_search($number[$i - 1], $fromBase), bcpow($fromLen, $numberLen - $i)));
        }

        return $retval;
    }
    if ($fromBaseInput != '0123456789') {
        $base10 = convBase($numberInput, $fromBaseInput, '0123456789');
    } else {
        $base10 = $numberInput;
    }

    if ($base10 < strlen($toBaseInput)) {
        return $toBase[$base10];
    }

    while ($base10 != '0') {
        $retval = $toBase[bcmod($base10, $toLen)] . $retval;
        $base10 = bcdiv($base10, $toLen, 0);
    }
    return $retval;
}

$b36 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$b10 = '0123456789';
$b5 = '01234';
$b2 = '01';

$con = convBase('AUB9789LJLKA89', $b36, $b10); // 1849450200354407014857
$con = convBase('1849450200354407014857', $b10, $b36); // AUB9789LJLKA89

【讨论】:

    猜你喜欢
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    相关资源
    最近更新 更多