ByteBuffer causing underflow exception

6.6k views Asked by At

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

There are 1 answers

0
Petar Butkovic On BEST ANSWER

You need to set start index or rewind buffer;

int recieve = ByteBuffer.allocate(4).put(bytes).getInt(0);