Java 缩短UUID为22位

5次阅读

共计 979 个字符,预计需要花费 3 分钟才能阅读完成。

参考

http://stackoverflow.com/ques… 这里面 rharari 的回答,就是利用无符号右移,每 6 位转换为 64 制字符

http://blog.csdn.net/sskicgah… 这位仁兄也参考了别人的就不列举了

思路
UUID 为 128 位,取高低 64 位分别处理,转为 64 制字符,我没有按照 Base64 的字符表来,随着自己的性子惯了,也没有 3 字节转为 4 字节,参考别人直接 64 位每低 6 位转为 int 对应一个 64 制字符数组(这样其实最后一组只有 4 位转为 64 制字符)
public class GenerateShortUUID {
private final static char[] DIGITS64 = “0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_”.toCharArray();

public static String next() {
UUID u = UUID.randomUUID();
// return u.toString();
return toIDString(u.getMostSignificantBits()) + toIDString(u.getLeastSignificantBits());
}

private static String toIDString(long l) {
char[] buf = “00000000000”.toCharArray(); // 限定 11 位长度
int length = 11;
long least = 63L; // 0x0000003FL
do {
buf[–length] = DIGITS64[(int) (l & least)]; // l & least 取低 6 位
/* 无符号的移位只有右移,没有左移
* 使用“>>>”进行移位
*/
l >>>= 6;
} while (l != 0);
return new String(buf);
}

public static void main(String[] args) {
long time = System.currentTimeMillis();
for (int i=0; i<1000000L; i++) {
next();
}
System.out.println(System.currentTimeMillis() – time);
}
}
效率之前有测试过忘记了,应该还可以,你们测试过的话可以告诉我。

正文完
 0