BufferOverflowException while converting int to byte

I have an counter which counts from 0 to 32767

At each step, I want to convert the counter (int) to an 2 byte array.

I've tried this, but I got a BufferOverflowException exception:

byte[] bytearray = ByteBuffer.allocate(2).putInt(counter).array();
Jon Skeet
people
quotationmark

Yes, this is because an int takes 4 bytes in a buffer, regardless of the value.

ByteBuffer.putInt is clear about both this and the exception:

Writes four bytes containing the given int value, in the current byte order, into this buffer at the current position, and then increments the position by four.

...

Throws:
BufferOverflowException - If there are fewer than four bytes remaining in this buffer

To write two bytes, use putShort instead... and ideally change your counter variable to be a short as well, to make it clear what the range is expected to be.

people

See more on this question at Stackoverflow