/**
* 2进制字典
*/
private static final char[] DIGITS_2 = new char[]{'0', '1'};
/**
* 16进制字典
*/
private static final char[] DIGITS_16 = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* 64进制字典
*/
private static final char[] DIGITS_64 = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
10进制转为其他进制
/**
* 10进制转为其他进制
*
* @param num
* @param digits
* @return
*/
public static String enBinary(long num, char[] digits) {
char[] buf = new char[64];
int index = 64;
while (num / digits.length > 0) {
buf[--index] = digits[(int) (num % digits.length)];
num = num / digits.length;
}
//最后数据处理
buf[--index] = digits[(int) (num % digits.length)];
return new String(buf, index, (64 - index));
}
其他进制转为10进制
/**
* 其他经制转为10进制
*
* @param str
* @param digits
* @return
* @throws Exception
*/
public static long deBinary(String str, char[] digits) throws Exception {
char[] strArr = str.toCharArray();
long num = 0;
for (int i = 0; i < strArr.length; i++) {
num = num + getStrIndex(digits, strArr[i]) * (long) Math.pow(digits.length, (strArr.length - i - 1));
}
return num;
}
private static int getStrIndex(char[] di, char c) throws Exception {
for (int i = 0; i < di.length; i++) {
if (di[i] == c) {
return i;
}
}
throw new Exception("转换数和数字字典异常");
}
测试
public static void main(String[] args) throws Exception {
System.out.println(enBinary(100L * 10000 * 10000, DIGITS_64));
System.out.println(deBinary("JUC+QA", DIGITS_64));
}
…