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

后端 未结 10 1611
挽巷
挽巷 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:05

    If you have gmp extension:

    gmp_strval(gmp_init($x, 10), 62)
    
    0 讨论(0)
  • 2020-11-29 02:09
    function convertBase10ToBase62($num){
    $charset="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $rtn="";
    
    $n=$num;$base=62;
    while($n>0){
        $temp=$n%$base;
        $rtn=$charset[$temp].$rtn;
        $n=intval($n/$base);
    }
     return $rtn;
    }
    
    0 讨论(0)
  • 2020-11-29 02:20

    OLD: A quick and dirty solution can be to use a function like this:

    function toChars($number) {
       $res = base_convert($number, 10,26);
       $res = strtr($res,'0123456789','qrstuvxwyz');
       return $res;
    }
    

    The base convert translate your number to a base where the digits are 0-9a-p then you get rid of the remaining digits with a quick char substitution.

    As you may observe, the function is easily reversible.

    function toNum($number) {
       $res = strtr($number,'qrstuvxwyz','0123456789');
       $res = base_convert($number, 26,10);
       return $res;
    }
    

    By the way, what would you use this function for?


    Edit:

    Based on the question change and on the @jnpcl answer, here is a set of functions that performs the base conversion without using pow and log (they take half the time to complete the tests).

    The functions work for integer values only.

    function toBase($num, $b=62) {
      $base='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
      $r = $num  % $b ;
      $res = $base[$r];
      $q = floor($num/$b);
      while ($q) {
        $r = $q % $b;
        $q =floor($q/$b);
        $res = $base[$r].$res;
      }
      return $res;
    }
    
    function to10( $num, $b=62) {
      $base='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
      $limit = strlen($num);
      $res=strpos($base,$num[0]);
      for($i=1;$i<$limit;$i++) {
        $res = $b * $res + strpos($base,$num[$i]);
      }
      return $res;
    }
    

    The test:

    for ($i = 0; $i<1000000; $i++) {
      $x =  toBase($i);
      $y =  to10($x);
      if ($i-$y)
        echo "\n$i -> $x -> $y";
    }
    
    0 讨论(0)
  • 2020-11-29 02:20

    have an array of characters like:

    $chars = array(
        1 => 'a',
        2 => 'b',
        //....
        27 => 'A',
        28 => 'B'
    );
    
    function getCharacter($key)
    {
        if(array_key_exists($key, $chars[$key]))
            return $chars[$key];
        return false;
    }
    
    function getNumber($char)
    {
        return array_search($char, $chars);
    }
    
    0 讨论(0)
提交回复
热议问题