最初的答案建议使用基数为 36 的 BigInteger,但这对于 19 位数字是不够的。
我不知道是否有库可以转换为 base 62,但下面的人为示例让您了解如何做到这一点。输出是:
originalId = 999999999999999999
newId = bUI6zOLZTrh
检索OriginalId = 999999999999999999
使用base 62的基本原理如下:
- 如果原始编号是唯一的,那么新编号也将是唯一的,因为它们实际上是相同的编号(即存在一对一关系)
- 您可以以 N 为底表示
N ^ 11 11 位字符的数字(例如,以 10 为底,11 位数字可以介于 0 和 10 ^ 11 或 1000 亿之间)
- 最大的 19 位数字(以 10 为底)是 10 ^ 19 - 1
- 如果 N = 62,则有 62 ^ 11 = 5 * 10 ^ 19 种可能性,它大于 10 ^ 19,因此可以表示任何 19 位数字。实际上使用 base 54 就足够了。
示例代码(受 BigInteger 和 Long 类启发的算法 - 待添加异常处理):
class Base62 {
private static final BigInteger RADIX = BigInteger.valueOf(62);
private static final char[] DIGITS = {
'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', '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'
};
public static void main(String[] args) throws IOException {
String originalId = "999999999999999999";
System.out.println("originalId = " + originalId);
String newId = getBase62From10(originalId);
System.out.println("newId = " + newId);
String retrieveOriginalId = getBase10From62(newId);
System.out.println("retrieveOriginalId = " + retrieveOriginalId);
}
/**
*
* @param number a positive number in base 10
*
* @return the same number, in base 62
*/
public static String getBase62From10(String number) {
char[] buf = new char[number.length()];
int charPos = number.length() - 1;
BigInteger i = new BigInteger(number);
BigInteger radix = BigInteger.valueOf(62);
while (i.compareTo(radix) >= 0) {
buf[charPos--] = DIGITS[i.mod(radix).intValue()];
i = i.divide(radix);
}
buf[charPos] = DIGITS[i.intValue()];
return new String(buf, charPos, (number.length() - charPos));
}
/**
*
* @param number a positive number in base 62
*
* @return the same number, in base 10
*/
public static String getBase10From62(String number) {
BigInteger value = BigInteger.ZERO;
for (char c : number.toCharArray()) {
value = value.multiply(RADIX);
if ('0' <= c && c <= '9') {
value = value.add(BigInteger.valueOf(c - '0'));
}
if ('a' <= c && c <= 'z') {
value = value.add(BigInteger.valueOf(c - 'a' + 10));
}
if ('A' <= c && c <= 'Z') {
value = value.add(BigInteger.valueOf(c - 'A' + 36));
}
}
return value.toString();
}
}