UUID高效去除短横线
import java.util.UUID;
public class UUIDUtil {
/**
* 1111
*
* all 1 in 16 hexadecimal
*/
private static final long hexMod = 15L;
/**
* All possible chars for representing a number as a hex String
*/
private static final char[] digits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
public static String toHexString(UUID uuid) {
char[] array = new char[32];
long leastBits = uuid.getLeastSignificantBits();
for (int i = 31; i >= 16; i--) {
array[i] = digits[(int) (leastbits & hexmod)];
leastBits >>>= 4;
}
long mostBits = uuid.getMostSignificantBits();
for (int i = 15; i >= 0; i--) {
array[i] = digits[(int) (mostbits & hexmod)];
mostBits >>>= 4;
}
return new String(array);
}
public static String randomUUID() {
return toHexString(UUID.randomUUID());
}
}
算法背景:
标准UUID的toString返回的字符串带有短横线,
UUID.randomUUID().toString();
8b4e04f3-f68a-48c4-8c18-88c1f84530e5
使用replace方式去除短横线的效率不高。
UUID.randomUUID().toString().replace("-", "");
8b4e04f3f68a48c48c1888c1f84530e5