title: How to parse byte stream in Java properly
body: <p>Hello boys and girls. </p>
  
  <p>I'm developing a terminal based client application which communicates over TCP/IP to server and sends and receives an arbitary number of raw bytes. Each byte represents a command which I need to parse to Java classes representing these commands, for further use. </p>
  
  <p>My question how I should parse these bytes efficiently. I don't want to end up with bunch of nested ifs and switch-cases.</p>
  
  <p>I have the data classes for these commands ready to go. I just need to figure out the proper way of doing the parsing. </p>
  
  <p>Here's some sample specifications:</p>
  
  <blockquote>
    <p>Byte stream can be for example in
    integers:[1,24,2,65,26,18,3,0,239,19,0,14,0,42,65,110,110,97,32,109,121,121,106,228,42,15,20,5,149,45,87]</p>
    
    <p>First byte is 0x01 which is start of header containing only one byte. </p>
    
    <p>Second one is the length which is the number of bytes in certain
    commands, only one byte here also.</p>
    
    <p>The next can be any command where the first byte is the command, 0x02
    in this case, and it follows n number of bytes which are included in
    the command.</p>
    
    <p>So on. In the end there are checksum related bytes.</p>
  </blockquote>
  
  <p>Sample class representing the set_cursor command:</p>
  
  <pre><code>/**
   * Sets the cursor position.
   * Syntax: 0x0E | position
   */
  public class SET_CURSOR {
  
  private final int hexCommand = 0x0e;
  private int position;
  
  public SET_CURSOR(int position) {
  
  }
  
  public int getPosition() {
      return position;
  }
  
  public int getHexCommnad() {
      return hexCommand;
  }
  
  }
  </code></pre>