简体   繁体   中英

ByteBuffer causing underflow exception

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();
}

您需要设置起始索引或倒带缓冲区;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM