#989 – Formatting Numbers as Hexadecimal

You can represent an integer as a series of hexadecimal characters by using the hexadecimal format specifier in a format string.

In the examples below, we represent several integers using their hexadecimal characters.  We use the X notation in the format string to indicate that the number should be displayed as hex.

            Console.WriteLine("{0} = {0:X}", 10);    // A
            Console.WriteLine("{0} = {0:X}", 157);   // 9D = (9 * 16) + 13
            Console.WriteLine("{0} = {0:X}", 1024);  // 400 = (4 * 256)
            Console.WriteLine("{0} = {0:X}", 6975);  // 1B3F = (1 * 4096) + (11 * 256) + (3 * 16) + 15

989-001
You can include a digit after the X to indicate the number of minimum digits to be displayed. The hex number will be padded with zeroes to reach the desired width.

            Console.WriteLine("{0} = {0:X4}", 157);   // 009D

989-002

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #989 – Formatting Numbers as Hexadecimal

  1. Pingback: #990 – Converting Hexadecimal Strings to Numeric Data | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: