public static byte[] ParseHexString(string s)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
byte[] bytes;
if ((s.Length & 1) != 0)
{
s = "0" + s; // make length of s even
}
bytes = new byte[s.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
string hex = s.Substring(2 * i, 2);
try
{
byte b = Convert.ToByte(hex, 16);
bytes[i] = b;
}
catch (FormatException e)
{
throw new FormatException(
string.Format("Invalid hex string {0}. Problem with substring {1} starting at position {2}",
s,
hex,
2 * i),
e);
}
}
return bytes;
}