2

I have hex value 4396 eccd. If I convert it to floating point number using some online calculator, I get value as 301.85 which is correct.

But when I convert it using python, I get some different value:

>>> float.fromhex('0x4396eccd')
1133964493.0

can anyone please help me on why its showing wrong value in python. Thanks

1 Answer 1

2

For understanding what fromhex() do, you can refer this : https://python-reference.readthedocs.io/en/latest/docs/float/fromhex.html

Instead of using fromhex() for hex string to float number, you should better use struct module.

In python 2.x

>>> import struct
>>> struct.unpack('!f', '41973333'.decode('hex'))[0]
18.899999618530273

In python 3.x use:

bytes.fromhex('41973333') instead of '41973333'.decode('hex')

So it will be as follows:

>>> import struct
>>> struct.unpack('!f', bytes.fromhex('41973333'))[0]
18.899999618530273
Sign up to request clarification or add additional context in comments.

7 Comments

Your solution gives me this error: AttributeError: 'str' object has no attribute 'decode'
Sorry my bad. Check it again.
For me it is working. Did it worked for you? If it worked then please do mark it as solved and if not then please let me know.
Thanks can you have a look at this question please stackoverflow.com/questions/60770615/…
I have answered that in a comment. @SAndrew
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.