How to convert GUID to Integer in C#

By FoxLearn 11/10/2024 11:32:35 AM   120
Converting a GUID to an integer in C# isn't a straightforward process because a GUID is a 128-bit value, while an integer in C# is only 32-bits.

 To convert GUID to integer without data loss, we cannot use Int32 or Int64.

.NET 4.0 introduced BigInteger struct which is 128 bit integer, and GUID can be easily converted to BigInteger as follows.

For example:

// ex: 6172d469-3e9e-4234-bc53-b90f77212d24  
Guid g = Guid.NewGuid();
Console.WriteLine(g);
// Convert GUID to BigInteger
// ex: 48086539959425620223526443617323504745
BigInteger bigInt = new BigInteger(g.ToByteArray());
Console.WriteLine(bigInt);

g.ToByteArray() converts the GUID to a 16-byte array.