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

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.

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

Or, you can put this into a loop to covert a Byte array to double values. Dim m as Integer = j.Length \ 8 Dim dble (m-1) as Double Dim k as Integer = 0

long bits = Double.doubleToLongBits(myDouble);

Hi All, I have requirement in which I need to convert 4 byte array into float value & 8 byte array into double value. If anybody knows how to do this conversion please let me know. Thanks.

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

I actually ran into problems with upper and lower of the double, this seems to be the only code I have seen that corrects for that. I hope it assists others searching for answers in this area. if you do go for some other code, make sure you test the full range of values, you should write a loop that converts to and from for all values and assert them to be sure.

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]

If you want to convert each double to a multi-byte representation, you can use the SelectMany method and the BitConverter class. As each double will result in an array of bytes, the SelectMany method will flatten them into a single result. byteArray = doubleArray.SelectMany(n => { return BitConverter.GetBytes(n); }).ToArray();

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

Go and Enjoy.

@Mehrdad et al, this is not the same question as ".NET String to byte Array C#". The question here is - how do I convert from a byte array to a string and back, safely. I use the "magical" Latin1 encoding (Encoding.GetEncoding( 28591 )) which seems to respect byte => string => byte nicely. – Liam Oct 18 '13 at 13:12

How do I convert a long to a byte[] and back in Java?. I'm trying convert a long to a byte[] so that I will be able to send the byte[] over a TCP connection. On the other side I want to take that byte[] and convert it back into a double.

If, say, the byte array was encoded simply with ASCII chars from the original string (assuming it can be), after the BlockCopy, each char will be squeezed with two such ASCII characters, which is clearly wrong.

char is 1 byte; float is 4 bytes; double is 8 bytes; Your code is trying to put a 4-byte value into a 2-byte buffer. That won't fit. Second, can you please explain why you want to convert float/double into a byte array?

Comments
  • How many bytes would you like? It would be possible, technically, to make an array of bytes that each hold only one bit of information, for example.
  • Pops: I think it's fair to imply that Octavian wants only the number of bytes necessary to store a complete representation of a double i.e. matching the internal double representation. In Java, this can be calculated with (int)(Double.Size/Byte.Size) .
  • Would be great to know how this compares to a hand-written conversion for performance.
  • return ByteBuffer.wrap(new byte[8]).putDouble(value).array() turns the first method into another one-liner
  • @cubiclettuce Sadly, array() is not required to return anything as the backing structure does not need to be a byte[]. That is, it may throw either UnsupportedOperationException or ReadOnlyBufferException in that order.
  • ByteBuffer.wrap(new byte[8]) does the trick. From the Java docs of ByteBuffer.wrap: "The new buffer will be backed by the given byte array"
  • 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[].
  • This is an incomplete answer - and you will find that the problem is in the other half; reconstituting the double is not just a matter of pushing (int)b[0] << 56 | (int)b[1] << 48 | (int)b[2] << 40 (...) through Double.longBitsToDouble(). The ByteBuffer solutions are by far more elegant and headache-free.
  • Maybe so, but are not possible from Java ME. This is a working solution. Thanks. +1
  • Combine this with Double.longBitsToDouble and the inverse and the answer is complete (glowcoder's answer).
  • I don't get it, why would I want to go via bits, when going from/to Double and Byte?
  • You can blast the entire array to the buffer with buf.asLongBuffer().put(longArray);