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

Viewed 17751

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?

3 Answers

This provides a Python implementation of the Java longBitsToDouble and doubleToLongBits operations. Convert the longs to/from byte sequences, eg., as:

def doubleToLongBits(d) : 
  bts = struct.pack('d',d)
  return MathLib.bytes2integer(bts)

def longBitsToDouble(x) : 
  bts = MathLib.integer2bytes(x)
  d, = struct.unpack('d',bytes(bts))
  return d
Related