将数字10转换为基数62(a-zA-Z0-9) [英] converting a number base 10 to base 62 (a-zA-Z0-9)
问题描述
例如:
echo convert(12324324);
//返回Yg3(这里的幻想示例)
PHP的 base_convert()
可以转换为36。
一个快速而肮脏的解决方案可以使用这样的功能:
函数toChars($ number){
$ res = base_convert($ number,10,26);
$ res = strtr($ res,'0123456789','qrstuvxwyz');
return $ res;
}
基本转换将您的号码转换为数字为0-9a的基数-p
那么你可以用快速的字符替换去除剩余的数字。
正如你所看到的,函数很容易可逆。
函数toNum($ number){
$ res = strtr($ number,'qrstuvxwyz','0123456789');
$ res = base_convert($ number,26,10);
return $ res;
}
顺便说一句,你将会使用这个功能?
编辑:
根据问题的更改和@jnpcl答案,一组函数执行基本转换,而不使用pow和log(它们需要一半的时间来完成测试)。
这些函数只适用于整数值
函数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;
}
函数to10($ num,$ b = 62){
$ base ='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$ limit = strlen($ num);
$ res = strpos($ base,$ num [0]); ($ i = 1; $ i $ $; $ i ++)
$ $ $ $ $ $ $ $ $ $ $ $ $ $
}
return $ res;
}
测试
<$ ($ i = 0; $ i< 1000000; $ i ++){
$ x = toBase($ i); p $ p $
$ y = to10($ x);
if($ i- $ y)
echo\ $ $ i - > $ x - > $ y;
}
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)
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;
}
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 would you use this function for?
Edit:
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;
}
The test
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屋!