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.
You get the best performance if you calculate the values from the character codes instead of creating substrings and parsing them.
Code in C#, that handles both upper and lower case hex (but no validation):
Usage:
As the code uses a few tricks, here a commented version: