Questions about GUID's: Are they always fixed in length, and is the middle number always 4?

前端 未结 3 2313
醉酒成梦
醉酒成梦 2021-02-19 18:55

I just generated a few million GUID\'s turned them into a String and got the length... it was always the same. Can I rely on this fixed length of the GUID when converting to St

相关标签:
3条回答
  • 2021-02-19 19:34

    Yes, the length is fixed and yes, the middle number is always 4 when you use the standard tostring format. Some of the bits in GUID (known as a UUID almost anywhere that isn't windows) are fixed to indicate things like version etc..

    http://en.wikipedia.org/wiki/Uuid

    EDIT I should add that the "4" only applies to Guids that have been generated according to the Guid.NewGuid algorithm as implemented in .NET. There is nothing to stop you from taking any arbitrary byte[16] and converting it to Guid. So, you can only bank on it being 4 for the current implementation of the algorithm in .Net. If you are getting Guids from another source, you can't bank on the 4. An update to .Net or possibly windows(depending if .Net uses its own or Windows' generator) may change the fixed numbers of the GUID

    e.g. the following is completely working code and will not have the 4 in position:

            var rand = new Random();
            var byteArray = new byte[16];
            rand.NextBytes(byteArray);
            var g = new Guid(byteArray);
    
    0 讨论(0)
  • 2021-02-19 19:50

    From the documentation on Guid.ToString (with no parameters):

    The value of this Guid, formatted as follows: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx where the value of the GUID is represented as a series of lowercase hexadecimal digits in groups of 8, 4, 4, 4, and 12 digits and separated by hyphens. An example of a return value is "382c74c3-721d-4f34-80e5-57657b6cbc27".

    So the answer is "yes", it will always be the same length.

    As for the 4, it is a version number (according to http://en.wikipedia.org/wiki/Uuid). Every GUID that you generate with that algorithm will have a 4 in that position, but older GUIDs will have a 1, 2, or 3. Future ones might have a 5 or something higher.

    0 讨论(0)
  • 2021-02-19 19:50

    No - a GUID does not have to be a type 4 UUID in fact many GUIDS under windows are UUID's of TYPE 1.

    Type 1 takes the primary MAC, a clock and a sequence. This in fact "Leaks" data since all the UUID1s that are created on the same system will have the same MAC. That is why most GUID functions will take this data and hash it and turn it into a hash-based UUID

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