1

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!

2
  • The offsets are a:0, b:1, c:5. Do you need the value to be big endian or little endian? Commented Nov 1, 2011 at 12:27
  • i set the byte order to Little Endian. But the problem is still there Commented Nov 1, 2011 at 12:29

2 Answers 2

3

The code works as it should, and if you indeed select bytes with index 1,2,3,4 they will yield the value 100:

ByteBuffer bbf = ByteBuffer.allocate(9);
bbf.put((byte) 10);
bbf.putInt(100);
bbf.putInt(55);
byte[] msg = bbf.array();

byte[] from4to8 = Arrays.copyOfRange(msg, 1, 5);

ByteBuffer buf2 = ByteBuffer.wrap(from4to8);
System.out.println(buf2.getInt());             // Prints 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.:

    Modifications to this buffer's content will cause the returned array's content to be modified, and vice versa.

Sign up to request clarification or add additional context in comments.

9 Comments

tried your code, with byte order as LittleEndian. I get the printed value as 1677721600
That's the value you get if you take bytes 0,1,2,3, instead of 1,2,3,4. (I.e. if you change from 1,5 to 0,4 in the example in my answer).
By the second note do you mean I have to convert each instance variable separately using different ByteBuffer object? If not please explain in detail
set also the byte order of buf2 to little endian
It simply says that you shouldn't use msg as an array containing a copy of the content of the bbf, it is the content of the bbf. If you have some lines in between, changing bbf the content of msg will change at the same time.
|
1

As far as I can see, B is at offset 1

1 Comment

Sorry for the typo. Correction made.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.