What is UUID ? Practically Explained.
What is UUID ?
A UUID (Universally Unique Identifier) is a 128 bit character sequence which is used to identify object or entity. This require’s no central registration for its generation so it is fairly easy to generate on the spot when needed. In this article we will learn how to generate UUID version 4 which is pseudo random generated version (PRNG). We’ll show you the code in java how to generate your own UUID. So lets begin.
Below is how sample UUID will look like,
00e8da9b-9ae8–4bdd-af76-af89bed2262f
What are the components of UUID ?
Two major components of UUID are variant and version. We have 4 variants and 5 version of UUID.
Variants (N) :

Versions (M):

Now every UUID have the version(M) and variant(N) embedded as shown below at 7th and 9th byte of sequence:
xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
Most common implementation is variant 1 where MSB0 is 1 and MSB1 is 0 followed by an wildcard, so combination’s we can achieve for N is shown below:
1 0 0 0 = 8
1 0 0 1 = 9
1 0 1 1 = B
1 0 1 0 = A
You will always see 7th byte as 4 and 9th byte be anything in (8, 9, B, A).
Algorithm:
PRNG is the easiest UUID to generate, but no guarantee can be made towards its uniqueness though, it all depends upon how efficient is your random number generator.
Simple recipe to generate it is as follows:
- Generate 128 random bits.
- Now overwrite 7th and 9th byte to place correct version (M) and variant (N) information as shown below.
- Take 7th byte and perform
AND
operation with0x0F
to clear out high nibble, this will give last 4 digit of any hexcode ex.8D
->10001101
after AND operation8D
&0x0F
->1101
. ThenOR
it with0x40
to set the version to 4. - Next, take 9th byte and perform
AND
operation with0x3F
. ThenOR
it with0x80
.
3. Convert the 128 bits to hexadecimal and insert hyphen (-)
.
Lets check out how it will be implemented in code:
Once you run the code you will see output with 7 byte as 4 representing version 4 and 9th byte belongs to (8, 9, B, A) that is variant 1.
240bc913–3954–45d7-a5fb-7f0b96077aff
f5816c30-c979–4ab6–8a68-c2c2e4ebf2c2
34013fad-bdef-43ea-929f-540be3aef500
34013fad-bdef-43ea-929f-540be3aef500
How much uniqueness you can achieve in long run ?
If you generate UUID with 1 billion UUID every second the probability of getting it duplicate would be 50% in very long run, off course this depends a lot on you random number generator algorithm.
Ref Links:
Research Paper: https://www.researchgate.net/publication/215758035_A_Universally_Unique_IDentifier_UUID_URN_Namespace