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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25736794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:02:16  来源:igfitidea点击:

java.nio.BufferUnderflowException while converting byte array to double

javaexceptiondoublebytearraybytebuffer

提问by Sushmita Bhattacharya

I need to convert a bytearray to double. I am using

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

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

But at the runtime I am getting BufferUnderflowException exception

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

What do I need to change here?

我需要在这里更改什么?

回答by Sotirios Delimanolis

ByteBuffer#getDouble()throws

ByteBuffer#getDouble()投掷

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

So valuemust contain less than 8 bytes. A doubleis a 64 bit, 8 bytes, data type.

所以value必须包含少于8个字节。Adouble是 64 位、8 字节的数据类型。

回答by user3145373 ツ

Your code be something like this :

你的代码是这样的:

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

If it is then it should work.

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

And show us your data of valuearray.

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

from the oracle docs:

来自 oracle文档

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

In order to fix it, you need to make sure that the ByteBufferhas enough data in it in order to read a double (8 bytes).

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

Look Here's a simple code to show what you want with input data and output.

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