短地址服务(一)

/**
 * @author 
 * @date: 2019-01-09 11:14
 * @des: 10进制转换62进制
 */
public class ConversionUtil {
    private static char[] charSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();

    /**
     * TODO 10进制到62进制
     *
     * @param number
     * @param length 转化成的62进制长度,不足length长度的话高位补0,否则不改变什么
     * @return
     */
    public static String ts_10_to_62(long number, int length) {
        Long rest = number;
        Stack<Character> stack = new Stack<Character>();
        StringBuilder result = new StringBuilder(0);
        while (rest != 0) {
            stack.add(charSet[new Long((rest - (rest / 62) * 62)).intValue()]);
            rest = rest / 62;
        }
        for (; !stack.isEmpty(); ) {
            result.append(stack.pop());
        }
        int result_length = result.length();
        StringBuilder temp0 = new StringBuilder();
        for (int i = 0; i < length - result_length; i++) {
            temp0.append('0');
        }
        return temp0.toString() + result.toString();
    }

    /**
     * TODO 62进制转换10进制
     * @param shortUrl 62进制值
     * @return
     */
    public static long ts_62_to_10(String shortUrl) {
        int multiple = 1;
        long result = 0;
        Character c;
        for (int i = 0; i < shortUrl.length(); i++) {
            c = shortUrl.charAt(shortUrl.length() - i - 1);
            result += ts_62_value(c) * multiple;
            multiple = multiple * 62;
        }
        return result;
    }

    private static int ts_62_value(Character c) {
        for (int i = 0; i < charSet.length; i++) {
            if (c == charSet[i]) {
                return i;
            }
        }
        return -1;
    }
}

 

posted @ 2019-03-04 20:53  瑾谦  阅读(326)  评论(0编辑  收藏  举报