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.

C#
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

NumberStyles Enum (System.Globalization)
Determines the styles permitted in numeric string arguments that are passed to the Parse and TryParse methods of the integral and floating-point numeric types.
https://learn.microsoft.com/en-us/dotnet/api/system.globalization.numberstyles
NumberStyles
Parsing Numeric Strings in .NET - .NET
Learn about parsing numeric strings in .NET. Learn how to parse with format providers, NumberStyles enumeration values, and Unicode digits.
https://learn.microsoft.com/en-us/dotnet/standard/base-types/parsing-numeric
Numeric parsing

Author: Herman Schoenfeld