可能重复:
有没有办法生成仅由数字组成的随机 UUID?
我不想在UUID
唯一的整数中有字符..如何做到这一点java
?
getMostSigBits()
andgetLeastSigBits()
获取长值。byte[]
.BigInteger
对象。BigInteger
toString() 将是一个可能为负数的 UUID。您可以通过将-
符号替换为 1 或其他类似技术来解决该问题。我还没有测试过这个,但是whatevs #gimmetehcodez
long hi = id.getMostSignificantBits();
long lo = id.getLeastSignificantBits();
byte[] bytes = ByteBuffer.allocate(16).putLong(hi).putLong(lo).array();
BigInteger big = new BigInteger(bytes);
String numericUuid = big.toString().replace('-','1'); // just in case
您需要 2long
秒来存储UUID
.
UUID myuuid = UUID.randomUUID();
long highbits = myuuid.getMostSignificantBits();
long lowbits = myuuid.getLeastSignificantBits();
System.out.println("My UUID is: " + highbits + " " + lowbits);
这将生成一个没有字符的 v4 UUID,但是它变得不那么独特了。
final int[] pattern = { 8, 4, 4, 4, 12 };
final int[] versionBit = { 2, 0 }; /* 3rd group, first bit */
final int version = 4;
final int[] reservedBit = { 3, 0 }; /* 4rd group, first bit */
final int reserved = 8; /* 8, 9, A, or B */
Random rand = new Random();
String numericUuid = "";
for (int i = 0; i < pattern.length; i++) {
for (int j = 0; j < pattern[i]; j++) {
if (i == versionBit[0] && j == versionBit[1])
numericUuid += version;
else if (i == reservedBit[0] && j == reservedBit[1])
numericUuid += reserved;
else
numericUuid += rand.nextInt(10);
}
numericUuid += "-";
}
UUID uuid = UUID.fromString(numericUuid.substring(0, numericUuid.length() - 1));
System.out.println(uuid);
您还可以使用以下代码进行暴力破解:
UUID uuid = UUID.randomUUID();
while (StringUtils.containsAny(uuid.toString(), new char[] { 'a', 'b', 'c', 'd', 'e', 'f' })) {
uuid = UUID.randomUUID();
}
System.out.println(uuid);