How to convert GUID to Integer in C#
By Tan Lee Published on Nov 10, 2024 841
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.
You can use Guid.GetHashCode()
to convert guid to 32-bit integer that represents the hash of the Guid
.
For example, guid to integer 32
Guid guid = Guid.NewGuid(); int result = guid.GetHashCode(); Console.WriteLine(result);
You can also extract the first 4 bytes from the Guid
and combine them into a 32-bit integer.
Guid guid = Guid.NewGuid(); int result = BitConverter.ToInt32(guid.ToByteArray(), 0); Console.WriteLine(result);
In this example:
guid.ToByteArray()
converts theGuid
into a byte array (16 bytes).BitConverter.ToInt32()
converts the first 4 bytes of the byte array into a 32-bit integer.
Categories
Popular Posts
Material Lite Admin Template
Nov 14, 2024
Simple Responsive Login Page
Nov 11, 2024
Freedash bootstrap lite
Nov 13, 2024
Dash UI HTML5 Admin Dashboard Template
Nov 18, 2024