1

I came across a problem when sending data over TCP with a custom protocol which relies on knowing the length of data so I decided that I could not send an int due to the size of the int could be different lengths (the int 10 has a length of 2 whereas the int 100 has a length of 3) so I decided to send a 4 byte representation of the int instead and thus I came across ByteBuffer.

With the following example I get a BufferUnderflowException

try
{
    int send = 2147483642;
    byte[] bytes = ByteBuffer.allocate(4).putInt(send).array(); // gets [127, -1, -1, -6]
    int recieve = ByteBuffer.allocate(4).put(bytes).getInt(); // expected 2147483642; throws BufferUnderflowException
    if (send == recieve)
    {
        System.out.println("WOOHOO");
    }
}
catch (BufferUnderflowException bufe)
{
    bufe.printStackTrace();
}
1
  • You've left out the flip(), but it seems pretty pointless. Throw it all away and use DataOutputStream.writeInt() and friends. Commented Sep 20, 2014 at 10:18

1 Answer 1

4

You need to set start index or rewind buffer;

int recieve = ByteBuffer.allocate(4).put(bytes).getInt(0);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.