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

前端 未结 3 2305
醉酒成梦
醉酒成梦 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);
    

提交回复
热议问题