C# 拆分十六进制字符串

本文关键字:字符串 十六进制 拆分 | 更新日期: 2023-09-27 18:36:56

好吧,我得到了我的十六进制字符串(数据包),例如"70340A01000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

表示 {70, 34, 0A, 01

C# 拆分十六进制字符串

, 00, 00, 00, 00, 00, 00, 00}

最短路径 (.NET 4+) 是(取决于长度或原点):

byte[] myBytes = BigInteger.Parse("70340A0100000000000000", NumberStyles.HexNumber).ToByteArray();
Array.Reverse(myBytes);
myStram.write(myBytes, 0, myBytes.Length);

对于以前的版本,string.length/2 还定义了字节数组的长度,而不是每个解析对可以填充的长度。这个字节数组可以如上所述写入流。

对于这两种情况,如果源字符串太长,并且想要避免使用较大的字节数组,请继续执行从源获取 N 个字符组的步骤。

这实际上很完美!很抱歉,如果您的代码也这样做,但我就是不明白。

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;