Convert int to hex with leading zeros

user2264990 picture user2264990 · Apr 10, 2013 · Viewed 42.9k times · Source

How to convert int (4 bytes) to hex ("XX XX XX XX") without cycles?

for example:

i=13 hex="00 00 00 0D"

i.ToString("X") returns "D", but I need a 4-bytes hex value.

Answer

CodesInChaos picture CodesInChaos · Apr 10, 2013

You can specify the minimum number of digits by appending the number of hex digits you want to the X format string. Since two hex digits correspond to one byte, your example with 4 bytes needs 8 hex digits. i.e. use i.ToString("X8").

If you want lower case letters, use x instead of X. For example 13.ToString("x8") maps to 0000000d.