#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