如果你的最终目的是送byte[]
,那么实际上你可以跳过中间步骤,并立即进行转换,从string
使用Encoding.ASCII.GetBytes
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);
来源
2016-04-15 17:44:21
Ian
是的,你发布的前两行很好用!不够感谢你!你是我心目中的天才! –
太棒了。很高兴知道那件事! :) – Ian