Search This Blog

Tuesday, September 01, 2009

Convert byte array to hex string

If you are like me and you regularly need to use byte arrays or hex string, you know that it is very handy to convert a byte array to a hex string.
I was always confused as to why the framework would not have a native method to do this, so I used to write my own little method to do it that looked something like this.

StringBuilder sb = new StringBuilder();
foreach (byte b in myByteArray)
{
sb.Append(b.ToString("X2"));
}
string hexString = sb.ToString();

But low and behold, the framework does have a native method that does this, I was just looking in the wrong place.

So in the BitConverter class there is a ToString method that takes a byte array as a parameter and spits out a nice hex string for you.

string hex = BitConverter.ToString(myByteArray);

No comments: