Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ByteBuffer class

I'm reading a byte[] from a device and trying to interpret it as an integer array in Java with the help of the ByteBuffer class but I'm getting an index out of bounds error. Look here:

byteBuffer.put(bytes); // put the array of bytes into the byteBuffer        

System.out.println("the value I want is " + byteBuffer.getInt(16*4)); // gives me the number I want, but I'd rather deal with an integer array like this:

System.out.println("the value I want is " + byteBuffer.asIntBuffer().get(16)); // index out of bounds? Why??
like image 456
Barodapride Avatar asked Aug 25 '26 04:08

Barodapride


1 Answers

The ByteBuffer class internally stores several properties of the buffer. The most important one being the position (of a virtual "cursor") in the buffer. This position can be read with byteBuffer.position(), and written with byteBuffer.position(123);.

The JavaDoc of ByteBuffer.asIntBuffer now states:

The content of the new buffer will start at this buffer's current position.

This means that, for example, when you have a ByteBuffer with a capacity of 16 elements, and the position() of this ByteBuffer is 4, then the resulting IntBuffer will only represent the remaining 12 elements.

After calling byteBuffer.put(bytes), the position of the byte buffer is advanced (depending on the length of the byte array). The IntBuffer that you are creating then has a smaller capacity, accordingly.

To solve this, you can call byteBuffer.rewind() or byteBuffer.position(0) after you called byteBuffer.put(bytes). (Which one is more appropriate depends on the intended usage pattern)

like image 195
Marco13 Avatar answered Aug 27 '26 17:08

Marco13