Liton
Liton

Reputation: 1438

How to convert an integer to fixed length hex string in C#?

I have an integer variable with max value of 9999.

I can convert to fixed length string (4-characters):

value.ToString("0000");

and I can convert it to hex:

value.ToString("X");

I want to convert it to a hex string of four characters (padded with 0 at the left if the value is converted to less than four digits hex value). I tried the following which didn't work.

value.ToString("0000:X");

OK, I can check the length of hex string and pad left with zeros.

But is there any straightforward way?

Upvotes: 18

Views: 19668

Answers (2)

Julien Lebosquain
Julien Lebosquain

Reputation: 41253

Use a number after the X format specifier to specify the left padding : value.ToString("X4")

Upvotes: 35

Jan Dragsbaek
Jan Dragsbaek

Reputation: 8101

String.Format( "{0:X2}", intValue)

Upvotes: 8

Related Questions