可能是重复问题:
如何将字节数组转换为十六进制字符串,反之亦然?
我需要一种高效快速的方法来进行此转换。我已经尝试过两种不同的方法,但它们对我来说不够高效。是否有其他快速的方法可以在实时应用程序中处理大量数据?
public byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length / 2).Select(x => Byte.Parse(hex.Substring(2 * x, 2), NumberStyles.HexNumber)).ToArray();
}
对我来说,上面那一个感觉更有效率。
public static byte[] stringTobyte(string hexString)
{
try
{
int bytesCount = (hexString.Length) / 2;
byte[] bytes = new byte[bytesCount];
for (int x = 0; x < bytesCount; ++x)
{
bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
}
return bytes;
}
catch
{
throw;
}