繁体   English   中英

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

[英]java.nio.BufferUnderflowException while converting byte array to double

我需要将 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)

我需要在这里改变什么?

ByteBuffer#getDouble()抛出

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

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

你的代码是这样的:

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

如果它是那么它应该工作。

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

来自oracle 文档

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

为了解决这个问题,你需要确保ByteBuffer有足够的数据来读取一个double (8 bytes)

Look Here这是一个简单的代码,用于显示输入数据和输出的内容。

对于遇到此问题的其他人,您必须将字节数组扩展到至少 8 个字节,因此您可以使用这种方法来实现:

byte [] bytes = { /* your values */ };
bytes = extendByteArray(bytes);

// create a ByteBuffer from the byte array
ByteBuffer buffer = ByteBuffer.wrap(bytes);

// convert the ByteBuffer to a double value using IEEE754 standard
double result = buffer.getDouble();

这是 function 的实现:

public static byte[] extendByteArray(byte[] input) {
    int length = input.length;
    int newLength = Math.max(length, 8);
    byte[] output = new byte[newLength];
    for (int i = 0; i < newLength - length; i++) {
        output[i] = 0;
    }
    System.arraycopy(input, 0, output, newLength - length, length);

    return output;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM