GUID, 30 character random string
I need to generate a unique string that is 30 characters in length. At first, I was going to generate a GUID and just remove the first two characters.
Guid.NewGuid().ToString("N").Substring(2);
Will removing the two first characters have a sig开发者_如何转开发nificant effect on the "uniqueness"? Is it something that I should be worried about?
Is there a better way of generating a random 30 character string that will be guaranteed to be unique?
Removing two hexadecimal characters or equivalently 8 bits from a GUID will make it less unique but 120 bits still make a quite good unique value. If you don't want to generate millions of ids every second it should be safe to remove some bits from the timestamp and uniquifier without risking a collision. See for example the Wikipedia for the structure of GUIDs.
An alternative solution would be to encode the GUID in Base64 or something like that if you are not constraint to hexadecimal characters only. 128 bits encoded in Base64 yield a string of length 24. Then you can even add another 6 random characters to pad the string to 30 characters making it even more unique.
Truncating a GUID loses the uniqueness. To understand why you should understand how a GUID is created. It consists of a few parts:
- 60 bits of timestamp
- 48 bits of computer identifier
- 14 bits of uniquifier
- 6 bits are fixed
By discarding the first two characters you are discarding the 8 most significant bits of the timestamp part. This article explains it well and the dangers of truncating GUIDs. It also explains how you could use the same technique used in GUIDs to create unique identifiers that are not globally unique but will be unique for more constrained circumstances.
As the other answerers said before me, if you just remove two characters from the GUID, then it will not be unique anymore.
But there's another way: it's possible to shorten a GUID to up to 20 characters without losing information or uniqueness by ASCII encoding.
Check out this blog post by Jeff Atwood:
Coding Horror: Equipping our ASCII Armor
精彩评论