GarennePb
GarennePb

Reputation: 49

How to convert hex to IEEE floating point python

I want to convert this hex string '8436d4ccd436d3333' to IEEE floating point. I've try to do this with struct.unpack but it's requires a string argument of length 4.

struct.unpack('>f', binascii.unhexlify('8436d999a436e0000'))

I'm using this website to verify if my conversion attempts are correct : https://gregstoll.dyndns.org/~gregstoll/floattohex/ but I can't find a way to do this.

Thanks for any help

Upvotes: 2

Views: 5155

Answers (1)

Mark Dickinson
Mark Dickinson

Reputation: 30561

At a guess, each hex string contains two single-precision floating-point values, not one, and the initial 8 is part of the whatever message protocol is being used, and not a part of either of those floats. With that guess, I get some plausible-looking numbers:

>>> struct.unpack('>ff', binascii.unhexlify('436d4ccd436d3333'))
(237.3000030517578, 237.1999969482422)
>>> struct.unpack('>ff', binascii.unhexlify('436d999a436e0000'))
(237.60000610351562, 238.0)

And to reinforce the plausibility, here's what I get by encoding the corresponding 1-digit-past-the-decimal-point values:

>>> binascii.hexlify(struct.pack('>ff', 237.3, 237.2))
b'436d4ccd436d3333'
>>> binascii.hexlify(struct.pack('>ff', 237.6, 238.0))
b'436d999a436e0000'

Upvotes: 2

Related Questions