What is the best way to convert a hexidecimal string to a byte array (.NET)?

Posted by Robert Wagner on Stack Overflow See other posts from Stack Overflow or by Robert Wagner
Published on 2009-03-26T08:21:45Z Indexed on 2010/04/16 9:33 UTC
Read the original article Hit count: 276

Filed under:
|
|

I have a hexidecimal string that I need to convert to a byte array. The best way (ie efficient and least code) is:

string hexstr = "683A2134";
byte[] bytes = new byte[hexstr.Length/2];
for(int x = 0; x < bytes.Length; x++)
{
    bytes[x] = Convert.ToByte(hexstr.Substring(x * 2, 2), 16);
}

In the case where I have a 32bit value I can do the following:

string hexstr = "683A2134";
byte[] bytes = BitConverter.GetBytes(Convert.ToInt32(hexstr, 16));

However what about in the general case? Is there a better built in function, or a clearer (doesn't have to be faster, but still performant) way of doing this?

I would prefer a built in function as there seems to be one for everything (well common things) except this particular conversion.

© Stack Overflow or respective owner

Related posts about .NET

Related posts about hexadecimal