I'm trying to convert IEEE 754 floats in hex to standard python floats.
The following works in Python 2.x :
foo ='4074145c00000005'
conv_pound = struct.unpack('!d', foo.decode('hex'))[0]
print(conv_pound)
and produces the following output (which is indeed the number that I want):
321.272460938
However, python 3 does not have a str.decode method and I'm struggling to find how to do this. Any tips ?
In Python 3, we use "string". encode() and "string". decode() to convert an Unicode string to a bytes string, or convert a bytes string to an Unicode string. In Python 2, we have str() and unicode() , we can encode() and decode() to them, too.
hex() function in Python hex() function is one of the built-in functions in Python3, which is used to convert an integer number into it's corresponding hexadecimal form. Syntax : hex(x) Parameters : x - an integer number (int object) Returns : Returns hexadecimal string.
To convert Python String to hex, use the inbuilt hex() method. The hex() is a built-in method that converts the integer to a corresponding hexadecimal string. For example, use the int(x, base) function with 16 to convert a string to an integer.
bytes.fromhex()
worked for me in python3:
Python 3.6.6 (default, Sep 12 2018, 18:26:19)
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> foo ='4074145c00000005'
>>> import struct
>>> struct.unpack('!d', bytes.fromhex(foo))
(321.2724609375003,)
>>> struct.unpack('!d', bytes.fromhex(foo))[0]
321.2724609375003
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With