package com.ssyf.common.core.util;



/**
 * 转换工具
 * @author huwei
 * @date 2022/7/21 7:24
 */
public class ConvertUtil {
    /**
     * 62进制基本字符
     */
    private static final String SYSTEM62_STRING = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    /**
     * 转换为62进制
     * @author huwei
     * @date 2022/7/21 7:26
     */
    public static final String toSystem62(int num){
        StringBuffer sb = new StringBuffer();
        int temp = num;
        int len = SYSTEM62_STRING.length();
        while (temp >= 0){
            int mod = temp % len;
            sb.append(SYSTEM62_STRING.charAt(mod));
            if(temp < len){
                break;
            }
            temp = temp / len;
        }
        return sb.reverse().toString();
    }

    /**
     * 62进制转换为10进制
     * @param str
     * @return
     */
    public static final int system62ToInt(String str){
        int res = 0;
        for(int i = 0 ;i < str.length() ;++i){
            int idx = SYSTEM62_STRING.indexOf(str.charAt(i));
            if(idx == -1){
                throw new RuntimeException("["+str+"]不是62为进制字符串");
            }
            if(i < str.length() - 1){
                res += idx * Math.pow(SYSTEM62_STRING.length() ,str.length() - i - 1);
            }else{
                res += idx;
            }
        }
        return res;
    }
}
