問題描述
我有一個以 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";
}
這篇關于將數字基數 10 轉換為基數 62 (a-zA-Z0-9)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!