Is there a way to generate a random UUID, which consists only of numbers?

后端 未结 10 1483
一生所求
一生所求 2020-12-09 09:27

Java\'s UUID class generates a random UUID. But this consists of letters and numbers. For some applications we need only numbers. Is there a way to generate random UUID that

相关标签:
10条回答
  • 2020-12-09 09:33

    Why don't just generate Random number and put it into format you want?

    This won't give you uniqueness out of the box. (i.e. You will have to implement check on each generation and retry logic)

    Where as other solutions which are taking UUID bits and converting them to number will be more granular in uniqueness. depending on your usecase you might still want to check uniqueness with this approach.

    0 讨论(0)
  • 2020-12-09 09:37
    UUID uuid = UUID.randomUUID();
    String numericUUID = Long.toString(uuid.getMostSignificantBits())
                       + Long.toString(uuid.getLeastSignificantBits());
    
    0 讨论(0)
  • 2020-12-09 09:39

    Random is not universally unique. If you want to use UUIDs as opposed to the Random class as suggested by others, you could simply use a regex to strip out everything except numerics from the UUID. Try something like this,

    String id = UUID.randomUUID().toString().replaceAll("[^0-9]", "");

    0 讨论(0)
  • 2020-12-09 09:40

    The simpliest way:

    uuid.uuid4().int
    
    0 讨论(0)
  • 2020-12-09 09:42

    For the record: UUIDs are in fact 128 bit numbers.

    What you see as an alphanumeric string is the representation of that 128 bit number using hexadecimal digits (0..9A..F).

    The real solution is to transform the string into it's correspondent 128 bit number. And to store that you'll need two Longs (Long has 64 bit).

    0 讨论(0)
  • 2020-12-09 09:47

    If you dont want a random number, but an UUID with numbers only use:

    String lUUID = String.format("%040d", new BigInteger(UUID.randomUUID().toString().replace("-", ""), 16));
    

    in this case left padded to 40 zeros...

    results for:
    UUID : b55081fa-9cd1-48c2-95d4-efe2db322a54
    in:
    UUID : 0241008287272164729465721528295504357972

    0 讨论(0)
提交回复
热议问题