简体   繁体   English

解析包含不同类型数据的字节数组

[英]Parsing byte array that contains different types of data

I have a fixed-length byte array that is 1250 bytes long. 我有一个1250字节长的固定长度字节数组。 It may contain the following types of data: 它可能包含以下类型的数据:

  • Object A which consists of 5 bytes. 对象A由5个字节组成。 The first byte contains the letter "A" and the next four bytes store an integer from 1 - 100000. 第一个字节包含字母“A”,接下来的四个字节存储1到100000的整数。

  • Object B which consists of 2 bytes. 对象B由2个字节组成。 The first byte contains the letter "B" and the next byte contains an integer from 1 - 100. 第一个字节包含字母“B”,下一个字节包含1到100的整数。

  • Object C which consists of 50 bytes. 对象C由50个字节组成。 All 50 bytes are used to store an ASCII-encoded string which will only consist of numbers and the following characters: - + ( and ) 所有50个字节用于存储ASCII编码的字符串,该字符串包含数字和以下字符: - +(和)

I don't know how many of each object type are in the byte array but I do know that they are grouped together (Object B, Object B, Object A, Object A, Object A, Object C, etc.). 我不知道每个对象类型有多少在字节数组中,但我知道它们被组合在一起(对象B,对象B,对象A,对象A,对象A,对象C等)。 Most of the time when I parse a byte array, the array contains data of one type (all items are Object A, for example) so I know exactly how many bytes each item is comprised of and I just loop through the array processing the bytes. 大多数情况下,当我解析一个字节数组时,该数组包含一种类型的数据(例如,所有项目都是对象A),所以我确切知道每个项目包含多少字节,我只是循环处理字节的数组。 In this case, I have three different types of data that are all different lengths. 在这种情况下,我有三种不同类型的数据,它们的长度都不同。 I was thinking that I would need to do something like this: 我以为我需要做这样的事情:

int offset = 0;
while (offset <= 1250)
{
    string objectHeader = Encoding.ASCII.GetString(byteArray, offset, 1);

    if (objectHeader.Equals("A"))
    {
        // read 4 more bytes and then convert into int value (1 - 100000)
        index += 5;
    }
    else if (objectHeader.Equals("B"))
    {
        // read 1 more byte and then convert into int value (1 - 100)
        index += 2;
    }
    else
    {
        // read 49 more bytes and then convert into a string
        index += 50;
    }
}

Is there a better way of doing this? 有没有更好的方法呢?

Well, there seems to be a little confusion with offset and index, maybe you should be using a for-loop: 好吧,似乎与偏移和索引有点混淆,也许你应该使用for循环:

for(int index = 0; index < 1250; index++)
{
    switch(byteArray[index])
    {
         case (byte)'A':
             index++;
             int value = BitConverter.ToInt32(byteArray, index);
             index += 4;
             break;

       case (byte)'B':
             index++;
             // Read the next byte as integer.
             int value = (int)byteArray[index];
             index++;
             break;

       case (byte)'C':  // string.
             index++;
             // Read the next 49 bytes as an string.
             StringBuilder value = new StringBuilder(49);
             for(int i = index; i < index + 49; index++)
             {
                 if (byteArray[i] == 0) break;
                 value.Append(Converter.ToChar(byteArray[i]));
             }
             index+= 49;
             break;

       case 0:  // Finished.
             index = 1250;
             break;
       default:
             throw new InvalidArgumentException("Invalid byte array format");
    }
}

How do you see if there is no more objects? 你如何看待没有更多的物体? In my example I suggest it ends with a '\\0'. 在我的例子中,我建议它以'\\ 0'结尾。

Good luck with your quest. 祝你好运。

      int offset = 0;
      while (offset <= 1250)
      {

        switch (byteArray[offset])
        {
          case (byte)'A':
            //read other data ..
            offset += 5;
            break;
          case (byte)'B':
            //read other data ..
            offset += 2;
            break;
          case (byte)'C':
            //read other data ..
            offset += 50;
            break;
          default:
            //error
            break;
        }
      } 

Or another variant with binary reader: 或二元阅读器的另一种变体:

      var reader = new BinaryReader(new MemoryStream(byteArray), Encoding.ASCII);
      while (reader.BaseStream.Position < reader.BaseStream.Length)
      {
        switch(reader.ReadChar())
        {
          case 'A':
            {
              var i = reader.ReadInt32();
              return new TypeA(i);
            }
            break;
          case 'B':
            {
              var i = reader.ReadByte();
              return new TypeB(i);
            }
            break;
          case 'C':
            {
              var chars = reader.ReadChars(49);
              return new TypeC(new string(chars.TakeWhile(ch => ch != 0).ToArray()));
            }
            break;
        }

      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM