beckah beckah - 2 months ago 19
Python Question

Reading hex to double-precision float python

I am trying to

a hex string to a double in Python.

When I try to unpack the following:

unpack('d', "4081637ef7d0424a");

I get the following error:

struct.error: unpack requires a string argument of length 8

This doesn't make very much sense to me because a double is 8 bytes long, and

2 character = 1 hex value = 1 byte

So in essence, a double of 8 bytes long would be a 16 character hex string.

Any pointers of unpacking this hex to a double would be super appreciated.


You need to convert the hex digits to a binary string first:

struct.unpack('d', "4081637ef7d0424a".decode("hex"))


struct.unpack('d', binascii.unhexlify("4081637ef7d0424a"))

The latter version works in both Python 2 and 3, the former only in Python 2