java 10進制與62進制相互轉換


直接上代碼:

import org.apache.commons.lang.StringUtils;

public class ConversionUtil {
    private static String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    private static int scale = 62;
    private static int minLength = 5;

    //數字轉62進制
    public static String encode(long num) {
        StringBuilder sb = new StringBuilder();
        int remainder;
        while (num > scale - 1) {
            //對 scale 進行求余,然后將余數追加至 sb 中,由於是從末位開始追加的,因此最后需要反轉字符串
            remainder = Long.valueOf(num % scale).intValue();
            sb.append(chars.charAt(remainder));
            //除以進制數,獲取下一個末尾數
            num = num / scale;
        }
        sb.append(chars.charAt(Long.valueOf(num).intValue()));
        String value = sb.reverse().toString();
        return StringUtils.leftPad(value, minLength, '0');
    }

    //62進制轉為數字
    public static long decode(String str) {
        //將 0 開頭的字符串進行替換
        str = str.replace("^0*", "");
        long value = 0;
        char tempChar;
        int tempCharValue;
        for (int i = 0; i < str.length(); i++) {
            //獲取字符
            tempChar = str.charAt(i);
            //單字符值
            tempCharValue = chars.indexOf(tempChar);
            //單字符值在進制規則下表示的值
            value += (long) (tempCharValue * Math.pow(scale, str.length() - i - 1));
        }
        return value;
    }
}

調用示例:

String num64 = ConversionUtil.encode(10000);
long num10 = ConversionUtil.decode(num64);

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM