Skip to content

Instantly share code, notes, and snippets.

@jorben
Last active August 11, 2022 08:21
Show Gist options
  • Save jorben/88e250d82095bdcc9b1a16b0ddc54c3c to your computer and use it in GitHub Desktop.
Save jorben/88e250d82095bdcc9b1a16b0ddc54c3c to your computer and use it in GitHub Desktop.
PHP 10进制和36进制转换
if (!function_exists('base36_encode')) {
/**
* 十进制数转换成三十六进制数
* @param (int)$num : 十进制数
* return (string) :三十六进制数
*/
function base36_encode($num)
{
$num = intval($num);
if ($num < 0)
{
return false;
}
$charArr = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
$char = '';
do
{
$key = bcmod($num , 36);
$char= $charArr[$key] . $char;
$num = bcdiv(($num - $key),36, 0);
}
while ($num > 0);
return $char;
}
}
if (!function_exists('base36_decode')) {
/**
* 三十六进制数转换成十进制数
* @param (string)$char :三十六进制数
* return (int) :十进制数
*/
function base36_decode($char){
$charArr = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
$len = strlen($char);
$sum = 0;
for($i=0; $i<$len; ++$i)
{
$index = array_search( $char[$i], $charArr);
$sum = bcadd($sum, bcmul($index, bcpow(36, $len-$i-1, 0)));
}
return $sum;
}
}
@jorben
Copy link
Author

jorben commented Jan 21, 2022

<?php

        // 测试用例
        $i = 88888888;
        $b36 = base36_encode($i);
        echo $i . ' = ' . $b36 . "\n";
        $x = base36_decode($b36);
        if ($x != $i) {
            echo 'error, x:' . $x . ' != i:' . $i. "\n";
        }

        $i = 0x7FFFFFFF;
        $b36 = base36_encode($i);
        echo $i . ' = ' . $b36 . "\n";
        $x = base36_decode($b36);
        if ($x != $i) {
            echo 'error, x:' . $x . ' != i:' . $i. "\n";
        }

        $i = 0xFFFFFFFF;
        $b36 = base36_encode($i);
        echo $i . ' = ' . $b36 . "\n";
        $x = base36_decode($b36);
        if ($x != $i) {
            echo 'error, x:' . $x . ' != i:' . $i. "\n";
        }

        $i = PHP_INT_MAX;
        $b36 = base36_encode($i);
        echo $i . ' = ' . $b36 . "\n";
        $x = base36_decode($b36);
        if ($x != $i) {
            echo 'error, x:' . $x . ' != i:' . $i. "\n";
        }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment