Console.WriteLine as hexadecimal

C#Hex

C# Problem Overview


The following code prints out 10. How can I make it print out a?

int i = 10;
Console.WriteLine("{0}", i);

C# Solutions


Solution 1 - C#

Console.WriteLine ("Hex: {0:X}", nNum);

The X formatter outputs uppercase hex chars. Use a lowercase x for lowercase hex chars.

Solution 2 - C#

i.ToString("x");

Solution 3 - C#

int i=10;
Console.WriteLine("{0:X4}", i);

Outputs hex with a size specifier.

you can also use string interpolation

int i=10;
Console.WriteLine($"{i:X4}");

Solution 4 - C#

int i=10;

Console.WriteLine("{0:x}", i);

or if you want 'A':

int i=10;

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

Solution 5 - C#

Int32 num = 1024;

Basic Hex Formatting

Using string interpolation:
Console.WriteLine("{0:X}", num);

Using built-in numeric string formatting:
Console.WriteLine(num.ToString("X"));

> 400

Fixed Precision Hex Formatting

Console.WriteLine(num.ToString("X4"));
> 0400

or

Console.WriteLine("0x{0:x8}", num);
> 0x00000400

Solution 6 - C#

You need to add a format specifier:

Console.WriteLine("{0:x}", i);

Solution 7 - C#

Change the format to {0:x}.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevin DriedgerView Question on Stackoverflow
Solution 1 - C#jscharfView Answer on Stackoverflow
Solution 2 - C#Neil NView Answer on Stackoverflow
Solution 3 - C#Paul BaxterView Answer on Stackoverflow
Solution 4 - C#Kevin DriedgerView Answer on Stackoverflow
Solution 5 - C#kayleeFrye_onDeckView Answer on Stackoverflow
Solution 6 - C#MiffTheFoxView Answer on Stackoverflow
Solution 7 - C#Daniel A. WhiteView Answer on Stackoverflow