原文地址:https://blog.csdn.net/qq_30629571/article/details/81065009
将10进制数字转成62进制数字
先定义62进制的代表字符:
1 static final char[] DIGITS = 2 { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 3 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 4 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 5 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 6 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 7 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
利用循环求余求商的原理编写方法:
1 private static String to62RadixString(long seq) { 2 StringBuilder sBuilder = new StringBuilder(); 3 while (true) { 4 int remainder = (int) (seq % 62); 5 sBuilder.append(DIGITS[remainder]); 6 seq = seq / 62; 7 if (seq == 0) { 8 break; 9 } 10 } 11 return sBuilder.reverse().toString(); 12 }
将62进制转换成10进制,反过来做
1 private static long radixString(String str) { 2 long sum = 0l; 3 int len = str.length(); 4 for (int i = 0; i < len; i++) { 5 sum += indexDigits(str.charAt(len-i-1))*Math.pow((double)62,(double)i); 6 7 } 8 return sum; 9 } 10 11 private static int indexDigits(char ch){ 12 for (int i = 0; i < DIGITS.length; i++) { 13 if (ch == DIGITS[i]){ 14 return i; 15 } 16 } 17 return -1; 18 }
同理,转任意进制的方式都可以这么做