title: java data types to byte array
body: <p>I have a Java class</p>
  
  <pre><code>public class MsgLayout{
  int field1;
  String field2;
  long field3;
  }
  </code></pre>
  
  <p>I have to write this object as a byte array in a Socket output stream. The three fields (instance variables) have a layout. i.e. <code>field1</code> must occupy 1 byte, <code>field2</code> must occupy 4 bytes and <code>field3</code> must occupy 8 bytes.</p>
  
  <pre><code>ByteBuffer bbf = ByteBuffer.allocate(TOTAL_SIZE);
  bbf.put(Integer.toString(this.getField1()).getBytes(), 0, FIELD1_SIZE);
  bbf.position(FIELD2_OFFSET);
  bbf.put(Long.toString(this.getField2()).getBytes(), 0, FIELD2_SIZE);
  bbf.position(FIELD3_OFFSET);
  bbf.put(Long.toString(this.getField3()).getBytes(), 0, FIELD3_SIZE);
  byte[] msg = bbf.array();
  </code></pre>
  
  <p>Using the above code, I am trying to fit each field in the byte array according to its desired size. But I am getting <code>IndexOutOfBoundException</code>
  In short, the problem is about how to fit the fields in the layout-defined size. For Example <code>FIELD1_OFFSET = 0, FIELD1_SIZE=1, FIELD2_OFFSET=1, FIELD2_SIZE=4, FIELD3_OFFSET=5, FIELD3_SIZE=8.</code>
  Now when I convert <code>field1</code> into String, it does not fit into 1 byte when converted into byte[]. If I do not convert to String, and use putInt(int) it writes 4 bytes into the resulting byte array.</p>