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

288次阅读
没有评论
<?php

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)
        ];

    }

}
正文完
有偿技术支持加微信
post-qrcode
 0
评论(没有评论)
验证码