55

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.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
Johnson
  • 698
  • 2
  • 6
  • 8
  • http://stackoverflow.com/questions/1139957/c-sharp-convert-integer-to-hex-and-back-again – Joetjah Apr 10 '13 at 07:51
  • @Joetjah Those answers only mention `X`, which the OP already knows. This question is about having leading `0` digits. – CodesInChaos Apr 10 '13 at 07:54
  • It's fine to close this as a duplicate if you find one, but the question you currently closed it as is no duplicate. The answers over there recommend `ToString("X")`, which doesn't produce the leading zeros the OP asked for. – CodesInChaos Apr 10 '13 at 15:05

2 Answers2

94

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.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
15

try this:

int innum = 123;
string Hex = innum .ToString("X");  // gives you hex "7B"
string Hex = innum .ToString("X8");  // gives you hex 8 digit "0000007B"
leiflundgren
  • 2,876
  • 7
  • 35
  • 53
KF2
  • 9,887
  • 8
  • 44
  • 77