php 十进制与62进制互转代码

作者: JONE 分类: 代码 发布时间: 2022-09-04 12:42
class Encode
{
    private static $dict = 'm1nQbAvZc2xWzaSsXd3fEgDhCj4kRlFpoVi5uTyGtBr6eYwHqN7UJM8IK9OL0P';

    /**
     * 62进制转10进制
     * @param $str
     * @return float|int
     */
    public static function from62To10(string $str){

        $len = strlen($str);
        $dec = 0;
        for($i = 0;$i<$len;$i++){
            //找到对应字典的下标
            $pos = strpos(self::$dict, $str[$i]);
            $dec += $pos*pow(62,$len-$i-1);
        }
        return $dec;
    }

    /**
     * 10进制转62进制
     * @param $dec
     * @return string
     */
    public static function from10To62(int $dec)
    {
        $result = '';
        do {
            $result = self::$dict[$dec % 62] . $result;
            $dec = intval($dec / 62);
        } while ($dec != 0);
        return $result;
    }

    /**
     * 根据时间戳生成唯一字符串并
     */
    public static function onlyStr($rand=null)
    {
        if(is_numeric($rand)){
            $rand_num =$rand;
        }else{
            $rand_num = rand(1, 999);
        }

        while (strlen($rand_num) < 3) {
            $rand_num = '0'.$rand_num;
        }

        $time = time(). $rand_num;

        $str = self::from10to62($time);

        return [
            'num' => $time,
            'str' => $str,
            'test' => self::from62to10($str)
        ];

    }

}