好吧,我得到了我的HexString(PacketS)例如“70340A0100000000000000”我想在2个字符之后每次分割并将其放入字节数组(Stream)。
表示{70,34,0A,01,00,00,00,00,00,00,00}
答案 0 :(得分:1)
最短路径(.NET 4+)是(取决于长度或原点):
byte[] myBytes = BigInteger.Parse("70340A0100000000000000", NumberStyles.HexNumber).ToByteArray();
Array.Reverse(myBytes);
myStram.write(myBytes, 0, myBytes.Length);
对于以前的版本,string.length / 2还定义了每个解析对可以填充的字节数组的长度。这个字节数组可以像上面那样在流上写入。
对于这两种情况,如果您的原始字符串太长,并且您想避免使用大字节数组,请继续执行从原点获取N个字符组的步骤。
答案 1 :(得分:0)
这实际上非常完美!我很抱歉,如果你的代码是一样的,但我只是不明白。
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[] HexAsBytes = new byte[hexString.Length / 2];
for (int index = 0; index < HexAsBytes.Length; index++)
{
string byteValue = hexString.Substring(index * 2, 2);
HexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return HexAsBytes;