public static byte[] ConvertHexStringToByteArray(string hexString)
{
if (hexString.Length % 2 != 0)
{
throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));
}
byte[] data = new byte[hexString.Length / 2];
for (int index = 0; index < data.Length; index++)
{
string byteValue = hexString.Substring(index * 2, 2);
data[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return data;
}
public static byte[] StrToByteArray(string str)
{
Dictionary<string, byte> hexindex = new Dictionary<string, byte>();
for (int i = 0; i <= 255; i++)
hexindex.Add(i.ToString("X2"), (byte)i);
List<byte> hexres = new List<byte>();
for (int i = 0; i < str.Length; i += 2)
hexres.Add(hexindex[str.Substring(i, 2)]);
return hexres.ToArray();
}
4 回答
这是一个非常有趣的LINQ示例 .
以下代码通过逐字节解析字符串将十六进制字符串更改为字节数组 .
我做了一些研究,发现byte.Parse甚至比Convert.ToByte慢 . 我能想到的最快转换使用每字节大约15个滴答 .
//也适用于.NET Micro Framework,其中(在SDK4.3中)byte.Parse(string)只允许整数格式 .
我认为这可行 .