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

15,822

Solution 1

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().

Solution 2

You want the struct module:

>>> d = 1.234
>>> b = struct.pack('d', d)
>>> b
b'X9\xb4\xc8v\xbe\xf3?'
>>> d2, = struct.unpack('d', b)
>>> d2
1.234

The pack method gives you a bytes in Python 3.x, or a str in Python 2.x. This type isn't mutable like a Java byte[], and in 2.x it also acts like a sequence of single-character strings, not a sequence of numbers from 0-255. If you need to fix either of those, just convert it to bytearray.

Also, note that—in both Java and Python—you probably want to specify an explicit endianness more often than not, especially if you're planning to save the bytes to a file or send them over the network. See Format Strings for details.

So:

>>> b = bytearray(struct.pack('!d', d))
>>> b
bytearray(b'?\xf3\xbev\xc8\xb49X')
>>> b[0]
63
Share:
15,822
user2426316
Author by

user2426316

Updated on June 20, 2022

Comments

  • user2426316
    user2426316 almost 2 years

    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?

  • user2426316
    user2426316 over 10 years
    How would you go about to extract doubles from the doubles_sequence. Say the first double.
  • Martijn Pieters
    Martijn Pieters over 10 years
    @user2426316: doubles_sequence[0] gives you the first value, just like in a list.