converting a number base 10 to base 62 (a-zA-Z0-9)

后端 未结 10 1698
挽巷
挽巷 2020-11-29 01:22

I have a number in base 10. Is there anyway to translate it to a base 62?

Example:

echo convert(12324324);
// returns Yg3 (fantasy example here)
         


        
10条回答
  •  清歌不尽
    2020-11-29 02:00

    It was hardly tested and works on real big product. Just copy this functions and use. If needed, you can arrange $baseChars sequentially, I need it for blended.

        /**
         * decToAny converter
         * 
         * @param integer $num
         * @param string $baseChars
         * @param integer $base
         * @return string
         */
        function decToAny($num, $baseChars = '', $base = 62, $index = false) {
    
            $baseChars = empty($baseChars) ? 'HbUlYmGoAd0ScKq6Er5PuZp3OsQCh4RfNMtV8kJiLv9yXeI1aWgFj2zTx7DnBw' : $baseChars;
            if (!$base) {
                $base = strlen($index);
            } else if (!$index) {
                $index = substr($baseChars, 0, $base);
            }
            $out = "";
    
            for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
                $a = floor($num / pow($base, $t));
                $out = $out . substr($index, $a, 1);
                $num = $num - ( $a * pow($base, $t) );
            }
    
            return $out;
        }
    

    Reverse method

        /**
         * anyTodec converter
         * 
         * @param string $num
         * @param string $baseChars
         * @param integer $base
         * @return string
         */
        function anyToDec($num, $baseChars = '', $base = 62, $index = false) {
    
            $baseChars = empty($baseChars) ? 'HbUlYmGoAd0ScKq6Er5PuZp3OsQCh4RfNMtV8kJiLv9yXeI1aWgFj2zTx7DnBw' : $baseChars;
            if (!$base) {
                $base = strlen($index);
            } else if (!$index) {
                $index = substr($baseChars, 0, $base);
            }
            $out = 0;
            $len = strlen($num) - 1;
            for ($t = 0; $t <= $len; $t++) {
                $out = $out + strpos($index, substr($num, $t, 1)) * pow($base, $len - $t);
            }
            return $out;
        }
    

提交回复
热议问题