pedrodbsa
pedrodbsa

Reputation: 1431

int to hex string

I need to convert an int to hex string.

When converting 1400 => 578 using ToString("X") or ToString("X2") but I need it like 0578.

Can anyone provide me the IFormatter to ensure that the string is 4 chars long?

Upvotes: 130

Views: 233856

Answers (5)

sadegh salehi
sadegh salehi

Reputation: 37

Convert int to hex string

int num = 1366;
string hexNum = num.ToString("X");

Upvotes: 2

0x777
0x777

Reputation: 945

Try C# string interpolation introduced in C# 6:

var id = 100;
var hexid = $"0x{id:X}";

hexid value:

"0x64"

Upvotes: 26

Mauro Raymondi
Mauro Raymondi

Reputation: 129

Previous answer is not good for negative numbers. Use a short type instead of int

        short iValue = -1400;
        string sResult = iValue.ToString("X2");
        Console.WriteLine("Value={0} Result={1}", iValue, sResult);

Now result is FA88

Upvotes: 5

Oded
Oded

Reputation: 499382

Try the following:

ToString("X4")

See The X format specifier on MSDN.

Upvotes: 18

Use ToString("X4").

The 4 means that the string will be 4 digits long.

Reference: The Hexadecimal ("X") Format Specifier on MSDN.

Upvotes: 202

Related Questions