Convert Numbers to and from Hexadecimal in C#

To show an integer in hexadecimal, format it with the X specifier. Uppercase X gives uppercase letters, lowercase x gives lowercase, and a number after it pads the result with leading zeros:

int value = 255;

Console.WriteLine(value.ToString("X"));   // FF
Console.WriteLine(value.ToString("x"));   // ff
Console.WriteLine(value.ToString("X4"));  // 00FF
Console.WriteLine($"0x{value:X2}");       // 0xFF

X never adds a 0x prefix; write it yourself as in the last line. Hex formatting does not depend on the culture, so you do not need to pass a CultureInfo here.

A few more values:

DecimalXX2x4
12C0C000c
6440400040
1237B7B007b
196C4C400c4
255FFFF00ff

Negative numbers

Hex output shows the two’s complement bits of the type, so the result depends on the size of the integer:

Console.WriteLine((-1).ToString("X"));          // FFFFFFFF
Console.WriteLine(((short)-1).ToString("X"));   // FFFF
Console.WriteLine(((sbyte)-1).ToString("X"));   // FF
Console.WriteLine((-1L).ToString("X"));         // FFFFFFFFFFFFFFFF

There is no minus sign. If you need -1 shown as -0x1, format Math.Abs(value) (careful with int.MinValue) and add the sign yourself.

Parse a hex string

int.Parse and int.TryParse read hex with NumberStyles.HexNumber. Use TryParse for anything that comes from a user or a file:

using System.Globalization;

if (int.TryParse("7B", NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int number))
{
    Console.WriteLine(number); // 123
}

NumberStyles.HexNumber does not accept a 0x prefix, so "0x7B" fails. Strip it first, for example with s.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? s[2..] : s.

Convert.ToInt32(string, 16) does accept the prefix, which makes it convenient for quick conversions. It throws a FormatException on invalid input, though, and has no Try variant:

Console.WriteLine(Convert.ToInt32("0x7B", 16)); // 123
Console.WriteLine(Convert.ToInt32("FF", 16));   // 255

Watch out for values with the top bit set. Both approaches read "FFFFFFFF" into an int as -1 rather than throwing an overflow error, because they interpret the digits as raw bits. Parse into uint or long if the value is meant to be positive:

Console.WriteLine(int.Parse("FFFFFFFF", NumberStyles.HexNumber));  // -1
Console.WriteLine(uint.Parse("FFFFFFFF", NumberStyles.HexNumber)); // 4294967295

Byte arrays and hex strings

For hashes, keys and binary protocols you usually convert a whole byte[]. Since .NET 5 there is a method for each direction:

byte[] bytes = [0xDE, 0xAD, 0xBE, 0xEF];

string hex = Convert.ToHexString(bytes);
Console.WriteLine(hex);                            // DEADBEEF

byte[] back = Convert.FromHexString("deadbeef");   // case-insensitive
Console.WriteLine(back.Length);                    // 4

Convert.ToHexString always returns uppercase. On .NET 9 and later, Convert.ToHexStringLower returns lowercase directly; on older versions call .ToLowerInvariant() on the result. FromHexString throws if the string has an odd length or contains anything other than hex digits, including spaces and dashes.

On .NET Framework, neither method exists. The usual workaround is BitConverter.ToString(bytes).Replace("-", ""), which produces the same uppercase string.

Literals and other bases

In source code, write hex literals with the 0x prefix and binary ones with 0b. Underscores can separate digit groups: 0xFF_FF and 0b1111_1111 are both valid.

For binary text, .NET 8 added a B format specifier for integers, so 255.ToString("B8") returns 11111111. On older versions use Convert.ToString(255, 2), which also handles base 8.

One quirk with System.Numerics.BigInteger: new BigInteger(255).ToString("X") returns 0FF. The leading zero is deliberate. Without it, FF would read back as a negative number, because BigInteger treats a hex string with the top bit set as negative.

Related examples

Leave a Comment