请解释一下这个 PHP 62 进制转换函数/算法
谁能解释一下下面的代码吗?或者向我指出一些资源,让我有所了解:)
它将整数转换为 base62 字符串。
private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
private static function _convertBase($num)
{
$base = strlen(self::$_characters);
$string = '';
for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
$a = floor($num / pow($base, $t));
$string .= substr(self::$_characters, $a, 1);
$num = $num - ($a * pow($base, $t));
}
return $string;
}
更新:我想问的是什么:有人可以解释一下下面的算法吗? :) 谢谢。
Could anyone please explain the code below? That or point me to some resources shedding some light :)
It converts an integer to a base62 string.
private static $_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
private static function _convertBase($num)
{
$base = strlen(self::$_characters);
$string = '';
for ($t = floor(log10($num) / log10($base)); $t >= 0; $t--) {
$a = floor($num / pow($base, $t));
$string .= substr(self::$_characters, $a, 1);
$num = $num - ($a * pow($base, $t));
}
return $string;
}
Update: What I meant to ask: Could anyone please explain the algorithm below? :) Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你太复杂了:
You're over-complicating:
使用对数时有一个公式:
logN(x) = log10(x) / log10(N)。
换句话说,以 N 为底的数字的对数等于该数字的对数(以 10 为底)除以底数的对数(同样以 10 为底)。
因此,您可以简单地使用本机 log10() 函数并相应地缩放数字,而不是为每个基数(例如基数 62)创建对数函数。
在这个特定的算法中,您想要确定要转换的数字以 62 为基数有多少位,因此您可以在“for”循环中使用它。
当然,您可以使用 while 循环来执行此操作,而无需计算 log62(n)。这是给读者的练习。
There is a formula when working with logarithms:
logN(x) = log10(x) / log10(N).
In other words, the log of a number in base N is equal to the log (in base 10) of the number divided by the log (again in base 10) of the base.
So instead of creating a logarithm function for each base, like base 62, you can simply use the native log10() function and scale the numbers accordingly.
And in this particular algorithm, you want to determine how many digits there are, in base 62, for the number you are converting, so you can use that in the "for" loop.
You could, of course, do this is with a while loop without having to calculate log62(n). This is an exercise for the reader.
一个更加伪代码的版本。
A more pseudocodey version.
希望这有帮助。
Hope this helps.