将数字基数 10 转换为基数 62 (a-zA-Z0-9)

我有一个以 10 为基数的数字.无论如何可以将其转换为以 62 为基数的数字吗?

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

示例:

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

PHP 的 base_convert() 最多可以转换为 base 36.

PHP's base_convert() can convert up to base 36.

推荐答案

OLD:一个快速而肮脏的解决方案可以是使用这样的函数:

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;
}

基数转换将您的数字转换为数字为 0-9a-p 的基数然后你用一个快速的字符替换去掉剩余的数字.

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?

根据问题的变化和@jnpcl 的回答,这里有一组函数可以在不使用 pow 和 log 的情况下执行基本转换(它们需要一半的时间来完成测试).

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;
}

测试:

for ($i = 0; $i<1000000; $i++) {
  $x =  toBase($i);
  $y =  to10($x);
  if ($i-$y)
    echo "
$i -> $x -> $y";
}

相关文章