How can I convert a byte array into a double and back?

Solution 1:

Or even simpler,

import java.nio.ByteBuffer;

public static byte[] toByteArray(double value) {
    byte[] bytes = new byte[8];
    ByteBuffer.wrap(bytes).putDouble(value);
    return bytes;
}

public static double toDouble(byte[] bytes) {
    return ByteBuffer.wrap(bytes).getDouble();
}

Solution 2:

long bits = Double.doubleToLongBits(myDouble);

Solution 3:

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),
    };
}

Solution 4:

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]

Solution 5:

public static final short byteArrayToShort(byte[] bytes) {
    return ByteBuffer.wrap(bytes).getShort();
}

public static final int byteArrayToInt(byte[] bytes) {
    return ByteBuffer.wrap(bytes).getInt();
}

public static final float byteArrayToFloat(byte[] bytes) {
    return ByteBuffer.wrap(bytes).getFloat();
}

public static double byteArrayToDouble(byte[] bytes) {
    return ByteBuffer.wrap(bytes).getDouble();
}

public static final long byteArrayToLong(byte[] bytes) {
    return ByteBuffer.wrap(bytes).getLong();
}

Hope it helps.