How to convert GUID to Integer in C#
By FoxLearn 3/10/2025 8:44:37 AM 501
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.
- How to use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#
Categories
Popular Posts
Portal HTML Bootstrap
11/14/2024
Carpatin Admin Dashboard Template
11/17/2024
Admin BSB Free Bootstrap Admin Dashboard
11/14/2024