views:

192

answers:

3

For converting a byte array to a double I found this:

//convert 8 byte array to double
int start=0;//???
int i = 0;
    int len = 8;
    int cnt = 0;
    byte[] tmp = new byte[len];
    for (i = start; i < (start + len); i++) {
        tmp[cnt] = arr[i];
        //System.out.println(java.lang.Byte.toString(arr[i]) + " " + i);
        cnt++;
    }
    long accum = 0;
    i = 0;
    for ( int shiftBy = 0; shiftBy < 64; shiftBy += 8 ) {
        accum |= ( (long)( tmp[i] & 0xff ) ) << shiftBy;
        i++;
    }

        return Double.longBitsToDouble(accum);

But I could not find anything which would convert a double into a byte array.

+6  A: 
long bits = Double.doubleToLongBits(myDouble);
glowcoder
I looked at your question - this isn't a complete answer - however, the same approach as above can be used in reverse if you really want a byte[].
glowcoder
A: 
public static byte[] toByteArray(double d) {
    long l = Double.doubleToRawLongBits(d);
    return new byte[] {
        (byte)((l >> 56) & 0xff),
        (byte)((l >> 48) & 0xff),
        (byte)((l >> 40) & 0xff),
        (byte)((l >> 32) & 0xff),
        (byte)((l >> 24) & 0xff),
        (byte)((l >> 16) & 0xff),
        (byte)((l >> 8) & 0xff),
        (byte)((l >> 0) & 0xff),
    };
}
JRL
+4  A: 

The functionality is implemented in the API already. Wrap the byte array in a ByteBuffer and use ByteBuffer.putLong and ByteBuffer.getLong:

import java.nio.*;
import java.util.Arrays;

public class Test {
    public static void main(String... args) throws Exception {

        long[] longArray = { 1234, 2345, 3456 };

        // Longs to bytes
        byte[] bytes = new byte[longArray.length * 8];
        ByteBuffer buf = ByteBuffer.wrap(bytes);
        for (long l : longArray)
            buf.putLong(l);

        System.out.println(Arrays.toString(bytes));

        // Bytes to longs
        ByteBuffer buf2 = ByteBuffer.wrap(bytes);
        long[] longs = new long[bytes.length / 8];
        for (int i = 0; i < longs.length; i++)
            longs[i] = buf2.getLong(i*8);

        System.out.println(Arrays.toString(longs));

    }
}

Output:

[0, 0, 0, 0, 0, 0, 4, -46, 0, 0, 0, 0, 0, 0, 9, 41, 0, 0, 0, 0, 0, 0, 13, -128]
[1234, 2345, 3456]
aioobe
Combine this with `Double.longBitsToDouble` and the inverse and the answer is complete (glowcoder's answer).
Kevin Brock
I don't get it, why would I want to go via bits, when going from/to Double and Byte?
aioobe