title: Parse a DatagramPacket after converting it to a byte array in Java
body: <p>I am trying to parse a DatagramPacket that I will receive at a socket. I know the format of the packet I will receive, which is a DHCPREQUEST packet, but I don't think that really matters. For simplicity's sake, let's just consider the first six fields:</p>
  
  <p>First field is the "opcode", which is 1 byte.<br>
  Second field is the "hardware type" which is 1 byte.<br>
  Third, "hardware address length", 1 byte.<br>
  Fourth, "hops", 1 byte.<br>
  Fifth, "transaction identifier xid", 4 bytes.<br>
  Sixth, "seconds", 2 bytes.</p>
  
  <p>After I receive the packet, my approach is to convert it to a byte array.</p>
  
  <pre><code>DatagramPacket request = new DatagramPacket(new byte[1024], 1024);
  socket.receive(request);
  byte[] buf = request.getData();
  </code></pre>
  
  <p>At this point, the packet is stored in the byte array <code>buf</code> as a series of bytes. Since I know what the structure of this byte sequence is, how can I parse it? The one-byte fields are simple enough, but how about the multiple-bit fields? For example, how can I extract bytes 4 to 7, and store them in a variable named <code>xid</code>?</p>
  
  <p>I could manually put each byte into an array:</p>
  
  <pre><code>byte[] xid = new byte[4];
  xid[0] = buf[4];
  xid[1] = buf[5];
  xid[2] = buf[6];
  xid[3] = buf[7];
  </code></pre>
  
  <p>But that's just tedious, and impractical for fields that are hundreds of bytes in length. The String class can parse substrings given an offset and length; is there a similar method for byte arrays in Java?</p>
  
  <p>Or am I somehow making things difficult for myself?</p>