The method does two different things and thus should be split in two:
- Interpret a hex string as a sequence of bytes. You can find many possible implementations at How do you convert Byte Array to Hexadecimal String, and vice versa?How do you convert Byte Array to Hexadecimal String, and vice versa?.
Yours has quadratic runtime (due to the string concatenation pattern RobH noted) and creates a new string object for each byte.
Keeping it similar to yours, but reducing it to linear runtime:
public static byte[] HexStringToBytes(string hexString)
{
if(hexString == null)
throw new ArgumentNullException("hexString");
if(hexString.Length % 2 != 0)
throw new ArgumentException("hexString must have an even length", "hexString");
var bytes = new byte[hexString.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
string currentHex = hexString.Substring(i * 2, 2);
bytes[i] = Convert.ToByte(currentHex, 16);
}
return bytes;
}
This code is still relatively slow, creating a new substring for each byte and using Convert.ToByte
, but I'd only complicate that after benchmarking revealed this as relevant cost.
- Interpret the sequence of bytes as an ISO-8859-1 encoded string. This is equivalent to your code, since the first 256 code-points in Unicode match the ISO-8859-1 single-byte encoding.
I'd use:
Encoding.GetEncoding("ISO-8859-1").GetString(bytes)
You should consider using UTF-8 instead, so you can support any Unicode code-point and not just those common in western Europe.