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)
基础教程推荐
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何替换eregi() 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
