I have a Java class
public class MsgLayout{
int field1;
String field2;
long field3;
}
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. field1
must occupy 1 byte, field2
must occupy 4 bytes and field3
must occupy 8 bytes.
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();
Using the above code, I am trying to fit each field in the byte array according to its desired size. But I am getting IndexOutOfBoundException
In short, the problem is about how to fit the fields in the layout-defined size. For Example FIELD1_OFFSET = 0, FIELD1_SIZE=1, FIELD2_OFFSET=1, FIELD2_SIZE=4, FIELD3_OFFSET=5, FIELD3_SIZE=8.
Now when I convert field1
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.