[英]Converting String to Hex then into Byte Array
因此,我有一个字符串,希望将每个字符转换为十六进制值,然后将其放入要通过com端口发送的字节数组中。
我可以将各个字符转换为需要发送的十六进制,但是我无法将字符串数组正确地转换为字节数组。
例:
string beforeConverting = "HELLO";
String[] afterConverting = {"0x48", "0x45", "0x4C", "0x4C", "0x4F"};
应该成为
byte[] byteData = new byte[]{0x48, 0x45, 0x4C, 0x4C, 0x4F};
我从多个不同的帖子中尝试了几种不同的方法,但是我无法将它们正确组合在一起。 如果有人可以向我指出正确的方向,或者给我一小段示例代码,那将是非常棒的!
如果您的最终目标是发送byte[]
,那么实际上您可以跳过中间步骤,并立即使用Encoding.ASCII.GetBytes
(假设您发送ASCII char)来完成从string
到byte[]
的转换:
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();
我上面介绍的方法比较笼统,可以处理0x05163782
类的输入string
以提供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);
要将十六进制字符串仅转换为数字,可以使用System.Convert类,如下所示
string hex = "0x3B";
byte b = Convert.ToByte(hex.Substring(2), 16)
// b is now 0x3B
子字符串用于跳过字符0x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.