4

I'm not sure why the following example gives buffer overflow exception. Hope someone can explain why, and how i can do it correctly.

It's as simple as this:

ByteBuffer bf = ByteBuffer.allocate(4);
bf.order(ByteOrder.BIG_ENDIAN);
bf.putInt(8);
bf.putInt(7); // Throws exception

The goal: [0,0,8,7]

Thanks in advance!

Ikky
  • 2,826
  • 14
  • 47
  • 68

2 Answers2

7

An int is 4 bytes long so you should multiply 4 to the number of int you need to store in your ByteBuffer.

Sanjeev
  • 9,876
  • 2
  • 22
  • 33
1

The javadoc states

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

Your totalNumberOfBytes must not be big enough to fit 2 ints, ie. less than 8.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724