0

Possible Duplicates:
How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?
C# byte[] to hex string

I need to take this:

byte[] data = new byte[] { 1, 2, 3, 4 }

And turn it into something like this:

0x01020304

What is the best way to do this in C#?

Community
  • 1
  • 1
Michael Hedgpeth
  • 7,732
  • 10
  • 47
  • 66
  • See this: http://stackoverflow.com/questions/623104/c-byte-to-hex-string – Katie Kilian Jun 03 '11 at 16:00
  • Forgive me for the duplicate. I must lack the knowledge needed to understand this. I didn't see any of the other questions show how to put it in "0x01020304" format. Did I miss that anywhere? – Michael Hedgpeth Jun 03 '11 at 19:56

2 Answers2

1

For a single value:

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

Depending on what the array represents you can then do some string concatenating to put all the bits together.

mdm
  • 12,480
  • 5
  • 34
  • 53
1
StringBuilder sb = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
{
       sb.AppendFormat("{0:x2}", b)
}
return sb.ToString();
Shahin
  • 12,543
  • 39
  • 127
  • 205