124

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?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
pedrodbsa
  • 1,361
  • 3
  • 10
  • 12
  • 2
    Look at numerics formats [here](http://msdn.microsoft.com/en-us/library/dwhawy9k(VS.71).aspx). – Ariel Jan 14 '11 at 11:25

5 Answers5

188

Use ToString("X4").

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

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

Sebastian Paaske Tørholm
  • 49,493
  • 11
  • 100
  • 118
19

Try C# string interpolation introduced in C# 6:

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

hexid value:

"0x64"
0x777
  • 825
  • 8
  • 14
18

Try the following:

ToString("X4")

See The X format specifier on MSDN.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
3

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

0

Convert int to hex string

int num = 1366;
string hexNum = num.ToString("X");
Blanket Fox
  • 377
  • 4
  • 15
sadegh salehi
  • 11
  • 1
  • 3