Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading hex to double-precision float python

Tags:

python

hex

I am trying to unpack 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.

like image 417
beckah Avatar asked Aug 08 '16 14:08

beckah


1 Answers

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

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

or

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

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

like image 86
Sven Marnach Avatar answered Nov 03 '22 17:11

Sven Marnach