Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 463
Liton Avatar asked Feb 15 '11 07:02

Liton


People also ask

Which method converts an integer to a hexadecimal string?

toHexString() method in Java converts Integer to hex string. Let's say the following are our integer values. int val1 = 5; int val2 = 7; int val3 = 13; Convert the above int values to hex string.

Does Atoi convert hex?

atoi(s[,base]) converts a string into an integer. The default is decimal, but you can specify octal 8, hexadecimal 16, or decimal 10. If 0 is the base, the string will be parsed as a hexadecimal if it has a leading 0x and as an octal if it has a leading 0. Otherwise, it will be treated as a decimal.

Which method converts an int value into its equivalent hexadecimal?

An integer can be converted to a hexadecimal by using the string. ToString() extension method.


2 Answers

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

like image 164
Julien Lebosquain Avatar answered Nov 03 '22 11:11

Julien Lebosquain


String.Format( "{0:X2}", intValue)
like image 9
Jan Dragsbaek Avatar answered Nov 03 '22 10:11

Jan Dragsbaek