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

1

8

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?

Preponderant answered 18/5, 2020 at 13:20 Comment(3)
UUID version 4Frey
Also, you're not going to generate a duplicate: "on the order 2³⁰ personal computers in the world ... if each one can generate, say, 2²⁰ GUIDs per second ... odds of collision get pretty good after only thirty trillion years."Frey
@Frey Yeah, just wanted to test it out myself. :P Thanks for the link!Preponderant
H
7

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!

Hernando answered 18/5, 2020 at 13:24 Comment(1)
Oh I see, perhaps I should've dug a little bit deeper before asking it here. But thank you for the quick reply!Preponderant

© 2022 - 2024 — McMap. All rights reserved.