如果您的最终目标是发送byte[],那么您实际上可以跳过中间步骤,立即使用Encoding.ASCII.GetBytes 将string 转换为byte[](前提是您发送ASCII 字符):
string beforeConverting = "HELLO";
byte[] byteData = Encoding.ASCII.GetBytes(beforeConverting);
//will give you {0x48, 0x45, 0x4C, 0x4C, 0x4F};
如果您不发送 ASCII,您可以根据需要找到合适的编码类型(如 Unicode 或 UTF32)。
话虽如此,如果您仍想将十六进制字符串转换为字节数组,您可以执行以下操作:
/// <summary>
/// To convert Hex data string to bytes (i.e. 0x01455687) given the data type
/// </summary>
/// <param name="hexString"></param>
/// <param name="dataType"></param>
/// <returns></returns>
public static byte[] HexStringToBytes(string hexString) {
try {
if (hexString.Length >= 3) //must have minimum of length of 3
if (hexString[0] == '0' && (hexString[1] == 'x' || hexString[1] == 'X'))
hexString = hexString.Substring(2);
int dataSize = (hexString.Length - 1) / 2;
int expectedStringLength = 2 * dataSize;
while (hexString.Length < expectedStringLength)
hexString = "0" + hexString; //zero padding in the front
int NumberChars = hexString.Length / 2;
byte[] bytes = new byte[NumberChars];
using (var sr = new StringReader(hexString)) {
for (int i = 0; i < NumberChars; i++)
bytes[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
}
return bytes;
} catch {
return null;
}
}
然后像这样使用它:
byte[] byteData = afterConverting.Select(x => HexStringToBytes(x)[0]).ToArray();
我上面的方法更通用,可以处理输入string,如0x05163782 给byte[4]。为了您的使用,您只需要获取第一个字节(因为byte[] 将始终为byte[1]),因此您在LINQ Select 中有[0] 索引。
上面自定义方法中使用的核心方法是Convert.ToByte():
bytes[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);