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

时间:2014-09-09 04:37:44

标签: java exception double bytearray bytebuffer

我需要将bytearray转换为double。我正在使用

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)

我需要在这里更改什么?

2 个答案:

答案 0 :(得分:13)

ByteBuffer#getDouble()抛出

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

因此value必须包含少于8个字节。 double是64位,8字节的数据类型。

答案 1 :(得分:2)

你的代码是这样的:

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

如果是,那么它应该有用。

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

来自oracle docs

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

为了解决这个问题,您需要确保ByteBuffer中有足够的数据才能阅读双(8 bytes)

查看Here这是一个简单的代码,可以显示输入数据和输出的内容。