php中的Base62类(适用于数值转字符串)
程序员文章站
2022-06-08 20:58:05
base62类源码:复制代码 代码如下:class base62 { private $string = "vph7zzwa2lyu4b...
base62类源码:
class base62 {
private $string = "vph7zzwa2lyu4bgq5tcvfimxji6xasok9cnp0owljythq8renmu31brdgedkfs";
public function base62_encode($str) {
$out = '';
for($t=floor(log10($str)/log10(62)); $t>=0; $t--) {
$a = floor($str / pow(62, $t));
$out = $out.substr($this->string, $a, 1);
$str = $str - ($a * pow(62, $t));
}
return $out;
}
public function base62_decode($str) {
$out = 0;
$len = strlen($str) - 1;
for($t=0; $t<=$len; $t++) {
$out = $out + strpos($this->string, substr($str, $t, 1)) * pow(62, $len - $t);
}
return substr(sprintf("%f", $out), 0, -7);
}
}
用法:
$str = 1;
$object = new base62();
echo $object->base62_encode($str) . "\n";
echo $object->base62_decode($object->base62_encode($str)) . "\n";
复制代码 代码如下:
class base62 {
private $string = "vph7zzwa2lyu4bgq5tcvfimxji6xasok9cnp0owljythq8renmu31brdgedkfs";
public function base62_encode($str) {
$out = '';
for($t=floor(log10($str)/log10(62)); $t>=0; $t--) {
$a = floor($str / pow(62, $t));
$out = $out.substr($this->string, $a, 1);
$str = $str - ($a * pow(62, $t));
}
return $out;
}
public function base62_decode($str) {
$out = 0;
$len = strlen($str) - 1;
for($t=0; $t<=$len; $t++) {
$out = $out + strpos($this->string, substr($str, $t, 1)) * pow(62, $len - $t);
}
return substr(sprintf("%f", $out), 0, -7);
}
}
用法:
复制代码 代码如下:
$str = 1;
$object = new base62();
echo $object->base62_encode($str) . "\n";
echo $object->base62_decode($object->base62_encode($str)) . "\n";
上一篇: Python3实现生成随机密码的方法