将数字基底10转换为基底62(a-zA-Z0-9) [英] converting a number base 10 to base 62 (a-zA-Z0-9)

查看:293
本文介绍了将数字基底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() 可以转换为36。

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

推荐答案

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

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
然后你用一个快速的char替换除去剩余的数字。

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 reversable.

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

顺便问一下,你会用这个函数做什么?

By the way, What do you would use this function for?

编辑

根据问题变化和@jnpcl答案,的函数执行基本转换,而不使用pow和log(它们需要一半时间来完成测试)。

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

这些函数仅对整数值起作用

The functions are working 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 "\n$i -> $x -> $y";
}

这篇关于将数字基底10转换为基底62(a-zA-Z0-9)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆