converting a number base 10 to base 62 (a-zA-Z0-9)(将数字基数 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";
}
这篇关于将数字基数 10 转换为基数 62 (a-zA-Z0-9)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将数字基数 10 转换为基数 62 (a-zA-Z0-9)


- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- PHP - if 语句中的倒序 2021-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01