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();
}
user3045798
  • 183
  • 1
  • 3
  • 11
  • You've left out the `flip()`, but it seems pretty pointless. Throw it all away and use `DataOutputStream.writeInt()` and friends. – user207421 Sep 20 '14 at 10:18

1 Answers1

4

You need to set start index or rewind buffer;

int recieve = ByteBuffer.allocate(4).put(bytes).getInt(0);
Petar Butkovic
  • 1,820
  • 15
  • 14