Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Guid.NewGuid always have a 4 in the exact same spot?

Tags:

.net

guid

random

I created a console application which just generated random GUIDs, but it came to my attention that it keeps having a 4 at the same location... Why is that?

Here's my code:

Sub Main()

    Dim generatedGuids = New List(Of String)
    Dim duplicateGenerated As Boolean = False
    Dim index As ULong = 0

    While Not duplicateGenerated

        Dim generatedGuid As String = Guid.NewGuid.ToString
        generatedGuids.Add(generatedGuid)

        duplicateGenerated = generatedGuids.Count <> generatedGuids.Distinct.Count

        index += 1

        Console.WriteLine(index & " - " & generatedGuid)


    End While

    Console.WriteLine("FOUND A DUPLICATE")

End Sub

(It's in VB.Net because I just took some online courses, and was playing around with it.)

Here's a screenshot:

enter image description here

As you can see, each generated GUID has a 4 at the exact same spot... Does anyone have an idea why?

like image 309
Mason Avatar asked May 18 '20 13:05

Mason


Video Answer


1 Answers

Not all 128 bits of a GUID are random.

This character represents the the UUID version (version 4 in your case), and the four bits of it are not supposed to be random.

There is another one :

The next first character after the next hyphen is not completely random as well, a few bits of it are determined and are actually coding the variant of the UUID version.

Notice that in your run, all the values of this last character are greater than or equal to 8, and less than c which means the hexadecimal value has always the first bits at 10 : 10xx, and it means you are using UUID version 4, variant 1.

see https://en.wikipedia.org/wiki/Universally_unique_identifier for more info.

And... that's all for the determined bits, so don't worry, your GUIDs are still unique!

like image 115
Pac0 Avatar answered Oct 01 '22 19:10

Pac0