Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DrayChou/7fddae442fc40fc29798a0903b20e684 to your computer and use it in GitHub Desktop.
Save DrayChou/7fddae442fc40fc29798a0903b20e684 to your computer and use it in GitHub Desktop.
<?php
/**
* 生成短连接的相关方法--通过记录ID换算成为58位的字符串(十进制转换成58进制)
*/
class BaseConvert {
const key_code_64 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
const key_code_58 = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
/**
* 十进制数转换成其它进制
* 可以转换成2-62任何进制
*
* @param integer $num
* @param integer $to
* @return string
*/
static function to($num, $to = 58) {
if ($to == 10 || $to > 64 || $to < 2) {
return $num;
}
if ($to == 58) {
$dict = self::key_code_58;
} else {
$dict = self::key_code_64;
}
$ret = '';
do {
$ret = $dict[bcmod($num, $to)] . $ret;
$num = bcdiv($num, $to);
} while ($num > 0);
return $ret;
}
/**
* 其它进制数转换成十进制数
* 适用2-62的任何进制
*
* @param string $num
* @param integer $from
* @return number
*/
static function from($num, $from = 58) {
if ($from == 10 || $from > 64 || $from < 2) {
return $num;
}
if ($from == 58) {
$dict = self::key_code_58;
} else {
$dict = self::key_code_64;
}
$num = strval($num);
$len = strlen($num);
$dec = 0;
for ($i = 0; $i < $len; $i++) {
$pos = strpos($dict, $num[$i]);
if ($pos >= $from) {
continue; // 如果出现非法字符,会忽略掉。比如16进制中出现w、x、y、z等
}
$dec = bcadd(bcmul(bcpow($from, $len - $i - 1), $pos), $dec);
}
return $dec;
}
/**
* 数字的任意进制转换
*
* @param integer|string $number
* @param integer $to 目标进制数
* @param integer $from 源进制数
* @return string
*/
static function radix($number, $to = 64, $from = 10) {
// 先转换成10进制
$number = self::from($number, $from);
// 再转换成目标进制
$number = self::to($number, $to);
return $number;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment