Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 964
user2426316 Avatar asked Dec 11 '13 21:12

user2426316


People also ask

Can a byte be cast to a double?

You can not cast from a double to byte because the byte has a range smaller than the double and it does not contain decimals like a double does.

What is a byte array in Python?

Python | bytearray() function bytearray() method returns a bytearray object which is an array of given bytes. It gives a mutable sequence of integers in the range 0 <= x < 256.


2 Answers

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

like image 80
Martijn Pieters Avatar answered Nov 14 '22 22:11

Martijn Pieters


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
like image 36
abarnert Avatar answered Nov 14 '22 22:11

abarnert