Parse and format hexadecimal integers in C#
Hexadecimal text is a representation of an integer. NumberStyles.HexNumber accepts hexadecimal digits but does not consume a 0x prefix, so remove that prefix deliberately before parsing.
Use an unsigned type for nonnegative bit patterns. Signed hexadecimal parsing can interpret a high leading bit as a negative two's-complement value.
Run a complete conversion
Create a .NET console project, replace Program.cs, and run dotnet run.
using System.Globalization;
var input = "0x00FF";
var digits = input.Trim();
if (digits.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
digits = digits[2..];
if (!uint.TryParse(digits, NumberStyles.HexNumber,
CultureInfo.InvariantCulture, out uint value)) {
Console.Error.WriteLine("Expected a hexadecimal UInt32 value.");
return;
}
Console.WriteLine(value);
Console.WriteLine(value.ToString("X8", CultureInfo.InvariantCulture));
The output is 255, followed by 000000FF. The X8 format specifies uppercase hexadecimal with at least eight digits. x selects lowercase. Use ulong when the input contract allows 64 bits.
Validate the intended width
An empty string, an invalid digit, or a value larger than UInt32.MaxValue returns false. A minimum output width is not an input-width restriction. Check the number of digits separately if a protocol requires exactly eight. Parse each byte separately when the source represents a byte sequence whose order matters. An integer conversion alone does not define endianness.
Official references


Author: Herman Schoenfeld