Search code examples
javapythondoublebyte

How can I convert a byte array to a double in python?


I am using Java to convert a double into a byte array. Like this:

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

Now, I would like to convert this byte array back into a double. In Java I would do it like this:

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

Now, how can I write the toDouble() method in Python?


Solution

  • Python has the struct module to convert bytes back to float values:

    import struct
    
    value = struct.unpack('d', bytes)[0]
    

    Here 'd' signifies that a double value is expected (in native endianess, as 8 bytes). See the module documentation for more options, including specifying endianess.

    Another option is to turn your bytes value into an array object; you'd use this is if you had a homogenous sequence of doubles:

    import array
    
    doubles_sequence = array.array('d', bytes)
    

    where every 8 bytes is interpreted as a double value, making doubles_sequence a sequence of doubles, addressable by index. To support a different endianess, you can swap the byte order with doubles_sequence.byteswap().