I am using ByteBuffer APIs to convert an object into bytes. The object’s class is as follows
public class Obj{
int a; // size 1 byte
int b; // size 4 bytes
int c; // size 4 bytes
}
Using ByteBuffer API, I have allocated an object
ByteBuffer bbf = ByteBuffer.allocate(9);
bbf.put((byte) this.getA());
bbf.putInt(this.getB());
bbf.putInt(this.getC());
byte[] msg = bbf.array();
I set the value of B as 100 but when I convert the byte array from offset 1 till length 4, I get a different integer value.
Any idea where is the problem?
thanks!
The code works as it should, and if you indeed select bytes with index 1,2,3,4 they will yield the value 100:
Some notes:
Keep in mind that the endian may differ from system to system (so check the endian on both hosts if this is part of a protocol)
The array you get from the
bbf.array()call is a backing array, i.e.: