Odrai Odrai - 1 year ago 95
C# Question

Is Guid.NewGuid().ToByteArray() to a string (number) line still unique

I need to generate a unique id which consists of numbers.

Is the following result string

as unique as the result of

Guid guid = Guid.NewGuid();
byte[] guidBytes = guid.ToByteArray();

// Is the result (uniqueId ) as unique as guid.ToString()?
string uniqueId = string.Join(string.Empty, guidBytes);

Answer Source

Yes, there is a 1:1 mapping of byte arrays to Guids. No information is lost during the transformation so you still retain the same uniqueness as using the normal string representation of a Guid.

A Guid really is just a 16 byte number, it does not matter if you show it as {3F2504E0-4F89-41D3-9A0C-0305E82C3301}, 4AQlP4lP00GaDAMF6CwzAQ== or as 224004037063137079211065154012003005232044051001, it all still represents the same number.

EDIT: Oops, as mkysoft ponted out, you do have to deal with leading zeros. Padding the numbers to 3 digits solves the issue

var guid = new Guid("{3F2504E0-4F89-41D3-9A0C-0305E82C3301}");
Console.WriteLine(string.Join(string.Empty, guid.ToByteArray().Select(x=>x.ToString("000"))));

UPDATE: Actually I just thought of a better solution, a Guid is a 128-bit number, by using 2 64-bit numbers and padding the number's 0's out on the 2nd half you will get a shorter, but still unique number.

var guid = new Guid("{3F2504E0-4F89-41D3-9A0C-0305E82C3301}");
var guidBytes = guid.ToByteArray();
Console.WriteLine("{0}{1}", BitConverter.ToUInt64(guidBytes, 0), BitConverter.ToUInt64(guidBytes,8).ToString().PadLeft(20, '0'));

This will output a unique integer number that is between 21 and 40 digits long, {3F2504E0-4F89-41D3-9A0C-0305E82C3301} becomes 474322228343976880000086462192878292122,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download