文章转自:PHP笔记 - E度笔记

/**
 * 十进制数转换成62进制
 *
 * @param integer $num
 * @return string
 */
function to62($num) {
    $to = 62;
    $dict = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $ret = '';
    do {
        $ret = $dict[bcmod($num, $to)] . $ret;
        $num = bcdiv($num, $to);
    } while ($num > 0);
    return $ret;
}


/**
 * 62进制数转换成十进制数
 *
 * @param string $num
 * @return string
 */
function from62($num) {
    $from = 62;
    $num = strval($num);
    $dict = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $len = strlen($num);
    $dec = 0;
    for($i = 0; $i < $len; $i++) {
        $pos = strpos($dict, $num[$i]);
        $dec = bcadd(bcmul(bcpow($from, $len - $i - 1), $pos), $dec);
    }
    return $dec;
}


/**
 * 十进制数转换成其它进制
 * 可以转换成2-62任何进制
 *
 * @param integer $num
 * @param integer $to
 * @return string
 */
function dec_to($num, $to = 62) {
    if ($to == 10 || $to > 62 || $to < 2) {
        return $num;
    }
    $dict = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $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
 */
function dec_from($num, $from = 62) {
    if ($from == 10 || $from > 62 || $from < 2) {
        return $num;
    }
    $num = strval($num);
    $dict = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $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
 */
function radix($number, $to = 62, $from = 10) {
    // 先转换成10进制
    $number = dec_from($number, $from);
    // 再转换成目标进制
    $number = dec_to($number, $to);
    return $number;
}

标签: php

添加新评论