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!

4
  • 1
    What is the total number of bytes? Commented May 16, 2014 at 13:48
  • haha, sorry. Forgot to insert a number instead of the variable. 4 Commented May 16, 2014 at 13:51
  • hmm, just a througt i got now... putInt is probably Int32? :P Commented May 16, 2014 at 13:52
  • @Ikky contrary to C in Java int has a fixed size of 32 bits Commented May 16, 2014 at 13:55

2 Answers 2

7

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

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

2 Comments

Yes, thought about that the minute after i asked :/ Thanks
If it helped you, kindly accept as answer :) Thanks
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.

Comments

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.