46

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
  • 100,017
  • 20
  • 197
  • 251
user2264990
  • 601
  • 2
  • 6
  • 6
  • 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

78

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
  • 100,017
  • 20
  • 197
  • 251
12

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,716
  • 7
  • 31
  • 53
KF2
  • 8,889
  • 8
  • 37
  • 76