C# Hex Numbers

Hex

Hex is a number representation. We use format strings and the ToString method to convert ints to hex format. The int.Parse method can then be used to convert them back.

This C# program reveals ways to use the hex format with ToString.

Hex example

To begin, the format string in the .NET Framework that converts to hexadecimal format is X. You can specify X and then a number (such as X8) to pad the output on the left side with zeros. The X format can be used with Console.WriteLine and ToString.

Program that handles hex number conversions [C#]

using System;
using System.Globalization;

class Program
{
    static void Main()
    {
	int value1 = 10995;

	// Write number in hex format.
	Console.WriteLine("{0:x}", value1);
	Console.WriteLine("{0:x8}", value1);

	Console.WriteLine("{0:X}", value1);
	Console.WriteLine("{0:X8}", value1);

	// Convert to hex.
	string hex = value1.ToString("X8");

	// Convert from hex to integer.
	int value2 = int.Parse(hex, NumberStyles.AllowHexSpecifier);
	Console.WriteLine(value1 == value2);
    }
}

Output

2af3
00002af3
2AF3
00002AF3
True
Question and answer

Convert from hex string to int. How can you convert in the reverse direction? The int.Parse method will not work correctly if you call it on the hex string with no other arguments. You can use the NumberStyles.AllowHexSpecifier argument to make it parse hex numbers.

Summary

The C# programming language

Hexadecimal numbers are encountered in many different scenarios in computer programs. They often represent memory locations. With the format strings x and X, we can encode integers into hexadecimal strings. With int.Parse and the AllowHexSpecifier constant, we can convert those hex strings back.

String Type
.NET