从较小的字节数组(Java)转换为long

Con*_*ine 2 java

我试图将一个字节数组转换为long,但接收BufferUnderflowException

    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    byte[] arg1 = new byte[] {0x04, (byte)0xB0};
    buffer.put(arg1, 0, arg1.length);
    buffer.flip();
    long val = buffer.getLong();
Run Code Online (Sandbox Code Playgroud)

在调试模式下,我查看了缓冲区内部.它有一个内部字节数组,它用"0"填充未指定的字节.那为什么会发生异常?我该如何解决?

Era*_*ran 5

的规范getLong()明确表示,它抛出BufferUnderflowException,如果there are fewer than eight bytes remaining in this buffer.您的缓冲区只有两个字节.