如何为数据消息中的不同段设置hex条目范围?

24个hex字节消息条目: xx xx xx xx xx xx xx xx xx xx xx xx

我有一个24个hex字节的消息输入到一个文本框中,具有不同的字节段入口要求,是否有一个模板代码供我动态编码每个段所需的hex值范围,例如1,4?

我尝试了下面的代码,但不是我想要的,因为它将整个hex条目转换为int等价物而不给我自由编码我想要的范围。

 outputTxt.Text = String.Join(" ", hexTextBox.Text.Trim().Split(' ').Select(item => Convert.ToInt32(item, 16))); 

例如,输入到文本框中的第一组2个hex值,检查输入的hex值的函数在0到100之间,在将其转换为十进制等效值到输出文本框之前,否则它将显示“错误”显示在输出文本框。

随后接下来的4个字节,我只允许4个字节的hex条目在-1000到1000之间的范围内显示“错误”消息。

编辑:很抱歉我之前如何对我的句子进行短语混淆,因为5个字节只是每个字节的ASCII字符的字节表示,范围为0到255.如何编码这些不同的情况? 谢谢!

 uint value1 = reader.ReadByte(); // 1 byte. if (value1 ==700) { OutputTxt.Text = value1.ToString(); OutputTxt.Text +="\n"; } else { OutputTxt.Text = "Error" OutputTxt.Text +="\n"; } uint value2 = reader.ReadByte(); // 1 byte. if (value2 <=1000) { OutputTxt.Text += value2.ToString(); OutputTxt.Text +="\n"; } else { OutputTxt.Text += "Error" OutputTxt.Text += "\n"; } 

我知道这可能是一个简单的错误,但我无法弄清楚正确的语法,以防止在运行第二次readByte()validation后重新更新我的第一个字节文本框?

我认为你最好的选择是这样做:

  1. 将hex字符串转换为字节数组。
  2. 使用MemoryStream包装数组并将其传递给BinaryReader以便更轻松地读取数据。
  3. 编写一个自定义方法,从流中读取所需的值并validation读取的值。

唯一棘手的问题是解析一组字节,这些字节不是整数类型的正常大小,例如5个字节。

这种情况的解决方案是在5个字节前加上3个零字节,然后使用BitConverter将其转换为long 。 例如:

 public static long LongFromBytes(byte[] bytes) { // This uses little-endian format. If you're expecting bigendian, you // would need to reverse the order of the bytes before doing this. return BitConverter.ToInt64(bytes.Concat(new byte[8-bytes.Length]).ToArray(), 0); } 

将hex字符串(带空格)转换为字节数组的合适方法是:

 public static byte[] StringToByteArray(string hex) { hex = hex.Trim().Replace(" ", ""); return Enumerable.Range(0, hex.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(hex.Substring(x, 2), 16)) .ToArray(); } 

现在,您可以将这些内容放在一起以validationhex字符串中的值:

 string hexString = "00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10 11 12 13 14 15 16 17 18"; using (var stream = new MemoryStream(StringToByteArray(hexString))) using (var reader = new BinaryReader(stream)) { int value1 = reader.ReadByte(); // 1 byte. Console.WriteLine(value1); int value2 = reader.ReadByte(); // 1 byte. Console.WriteLine(value2); int value3 = reader.ReadInt32(); // 4 bytes. Console.WriteLine(value3); long value4 = LongFromBytes(reader.ReadBytes(5)); // 5 bytes into a long. Console.WriteLine(value4); } 

读取值后,可以根据需要对其进行validation。