php-baseX

PHP-BASEX

  • 使用PHP实现进制之间转换,base2~base36
<?php
/**
 * Created by PhpStorm.
 * User: xiongchao
 * Date: 2018/7/9
 * Time: 14:18
 */

/*
 * 思路和普通的十进制转任意进制相同,假设将M进制转N进制,则基本思路为:M/N的余数的N进制表示作为结果的第一位,商的M进制表示作为下一论循环的输入。直到M为0为止。
 */

class BaseX{

    /**
     * @param string $num
     * @param int $m
     * @param int $n
     * @return string
     */
    public function baseConvert(string $num, int $m, int $n)
    {
        $result = '';
        $shang = $num;
        while (strlen($shang) > 0) {
            $result .= $this->qiuyu($shang, $m, $n);
        }
        return strrev($result);
    }

    private function qiuyu(string &$num, int $m, int $n)
    {
        $remain = 0;
        $shang = '';
        for ($i = 0; $i < strlen($num); $i++) {
            $remain = $remain * $m + $this->getIntFromStr($num[$i]);
            $shang .= $this->getStrFromInt(intval($remain / $n));
            $remain = $remain % $n;
        }
        while (strlen($shang) > 0 && $shang[0] == '0') {
            $shang = substr($shang, 1);
        }
        $num = $shang;
        return $this->getStrFromInt($remain);

    }

    private function getIntFromStr($value)
    {
        if ($value >= '0' && $value <= '9')
            return $value - 0;
        if ($value >= 'a' && $value <= 'z')
            return (ord($value) - ord('a')) + 10;
    }

    private function getStrFromInt(int $value)
    {
        if ($value >= 0 && $value <= 9)
            return (string)$value;
        if ($value >= 10 && $value <= 35)
            return chr(97 + ($value - 10));
        else
            throw new Exception("output $value");
    }

    /**
     * 依赖gmp扩展,该方法性能较好
     * @param string $num
     * @param $base
     * @param $toBase
     * @return string
     */
    public function gmp_convert(string $num,$base,$toBase){
        return gmp_strval(gmp_init($num,$base),$toBase);
    }
}