Console.WriteLine as hexadecimal
C#HexC# 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}
.