如何在java中创建整数UUID

时间:2012-06-06 20:48:59

标签: java integer uuid

  

可能重复:
  Is there a way to generate a random UUID, which consists only of numbers?

我不想在UUID只有整数中使用字符..如何在java中执行此操作?

4 个答案:

答案 0 :(得分:5)

  • 使用getMostSigBits()getLeastSigBits()获取长值。
  • 然后使用这些长值填充byte[]
  • 然后使用该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

答案 1 :(得分:3)

您需要2 long来存储UUID

UUID myuuid = UUID.randomUUID();
long highbits = myuuid.getMostSignificantBits();
long lowbits = myuuid.getLeastSignificantBits();
System.out.println("My UUID is: " + highbits + " " + lowbits);

答案 2 :(得分:1)

这将生成一个没有字符的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);

答案 3 :(得分:0)

如果你需要的只是一个随机数,用户Random类并致电nextInt()