Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console.WriteLine as hexadecimal

Tags:

c#

hex

People also ask

How do you write hex numbers in C#?

To represent Int32 as a Hexadecimal string in C#, use the ToString() method and set the base as the ToString() method's second parameter i.e. 16 for Hexadecimal. Int32 represents a 32-bit signed integer.

What is a hex string?

Hexadecimal Number String. The “Hexadecimal” or simply “Hex” numbering system uses the Base of 16 system and are a popular choice for representing long binary values because their format is quite compact and much easier to understand compared to the long binary strings of 1's and 0's.


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

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


i.ToString("x");


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}");

int i=10;

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

or if you want 'A':

int i=10;

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

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


You need to add a format specifier:

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

Change the format to {0:x}.