17

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

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?

3 Answers3

16

ByteBuffer#getDouble() throws

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

So value must contain less than 8 bytes. A double is a 64 bit, 8 bytes, data type.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
5

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 value array.

from the oracle docs :

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 ByteBuffer has enough data in it in order to read a double (8 bytes).

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

user3145373 ツ
  • 7,858
  • 6
  • 43
  • 62
  • I am fetching row from a HBase Table byte [] row1 = Bytes.toBytes(rowid); Get g = new Get(row1); Result result = table.get(g); byte[] value = result.getValue(Bytes.toBytes("columnfamily"), Bytes.toBytes("columnname")); But when printing System.out.print(value.length); I am getting 4 – Sushmita Bhattacharya Sep 09 '14 at 05:20
0

for others who have this problem, you have to extend byte array to be at least 8 bytes, so you can do it using this approach:

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();

and here is the function implementation:

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;
}
Homayoon Ahmadi
  • 1,181
  • 1
  • 12
  • 24