java.nio.BufferUnderflowException 同时将字节数组转换为双精度数组

2022-09-03 06:22:14

我需要将字节数组转换为双精度。我正在使用

double dvalue = ByteBuffer.wrap(value).getDouble();

但是在运行时,我得到了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)

我需要在此处更改哪些内容?


答案 1

ByteBuffer#getDouble() throws

 BufferUnderflowException - If there are fewer than eight bytes remaining in this buffer

因此必须包含少于 8 个字节。双精度值是 64 位 8 字节的数据类型。value


答案 2

你的代码是这样的:

byte [] value = { // values };
double dvalue = ByteBuffer.wrap(value).getDouble();

如果是这样,那么它应该有效。

并向我们展示您的阵列数据。value

来自预言机文档

Throws: BufferUnderflowException - If there are fewer than eight bytes remaining in this buffer

为了修复它,您需要确保 其中有足够的数据才能读取双精度。ByteBuffer(8 bytes)

查看 下面是一个简单的代码,用于显示输入数据和输出所需的内容。