title: Parsing byte array that contains different types of data
body: <p>I have a fixed-length byte array that is 1250 bytes long.  It may contain the following types of data:</p>
  
  <ul>
  <li><p>Object A which consists of 5 bytes.  The first byte contains the
  letter "A" and the next four bytes store an integer from 1 - 100000.</p></li>
  <li><p>Object B which consists of 2 bytes.  The first byte contains the letter "B" and the next byte contains an integer from 1 - 100.</p></li>
  <li><p>Object C which consists of 50 bytes.  All 50 bytes are used to store an ASCII-encoded string which will <strong>only</strong> consist of <strong>numbers</strong> and the following characters: - + ( and )</p></li>
  </ul>
  
  <p>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.).  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.  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:</p>
  
  <pre><code>int offset = 0;
  while (offset &lt;= 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;
      }
  }
  </code></pre>
  
  <p>Is there a better way of doing this?</p>