Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

uuid

random

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 consists of only numbers in Java?

UUID.randomUUID(); 
like image 844
rosh Avatar asked Nov 11 '11 10:11

rosh


People also ask

How unique is a random UUID?

Each character can be a digit 0 through 9, or letter a through f. 32 hexadecimals x log2(16) bits/hexadecimal = 128 bits in a UUID. In the version 4, variant 1 type of UUID, 6 bits are fixed and the remaining 122 bits are randomly generated, for a total of 2¹²² possible UUIDs.

Can random UUID be duplicate?

From the documentation and wikipedia we see that randomUUID is good - but there is a very small chance that duplicates can be generated.


2 Answers

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

like image 98
Chris Eibl Avatar answered Sep 27 '22 21:09

Chris Eibl


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).

like image 26
Pablo Pazos Avatar answered Sep 27 '22 20:09

Pablo Pazos