java.nio.BufferUnderflowException将字节数组转换为double

Sus*_*rya 12 java double bytebuffer bytearray exception

我需要将bytearray转换为double.我在用

double dvalue = ByteBuffer.wrap(value).getDouble();
Run Code Online (Sandbox Code Playgroud)

但是在运行时我得到了BufferUnderflowException异常

Exception in thread "main" java.nio.BufferUnderflowException
    at java.nio.Buffer.nextGetIndex(Buffer.java:498)
    at java.nio.HeapByteBuffer.getDouble(HeapByteBuffer.java:508)
    at Myclass.main(Myclass.java:39)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:212)
Run Code Online (Sandbox Code Playgroud)

我需要在这里更改什么?

Sot*_*lis 14

ByteBuffer#getDouble()

 BufferUnderflowException - If there are fewer than eight bytes remaining in this buffer
Run Code Online (Sandbox Code Playgroud)

所以value必须包含少于8个字节.A double是64位,8字节的数据类型.


use*_*3 ツ 5

你的代码是这样的:

byte [] value = { // values };
double dvalue = ByteBuffer.wrap(value).getDouble();
Run Code Online (Sandbox Code Playgroud)

如果是,那么它应该可以工作。

并向我们​​展示您的value数组数据。

来自 oracle文档

Throws: BufferUnderflowException - If there are fewer than eight bytes remaining in this buffer
Run Code Online (Sandbox Code Playgroud)

为了修复它,您需要确保其中ByteBuffer有足够的数据以读取 double (8 bytes)

看看这里有一个简单的代码来显示你想要的输入数据和输出。