Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert hex to float

How to convert the following hex string to float (single precision 32-bit) in Python?

"41973333" -> 1.88999996185302734375E1  "41995C29" -> 1.91700000762939453125E1  "470FC614" -> 3.6806078125E4 
like image 878
jack Avatar asked Oct 20 '09 02:10

jack


People also ask

How do you convert hex to float in Python?

int i = 0x41973333; float f = *((float*)&i); and that's exactly what the Python code using the ctypes library is doing in my example. I used your method to convert a hex string to float and it returns a wrong value.

How do you convert hex to bytes?

To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2]; Now, take a for loop until the length of the byte array.


1 Answers

In Python 3:

>>> import struct >>> struct.unpack('!f', bytes.fromhex('41973333'))[0] 18.899999618530273 >>> struct.unpack('!f', bytes.fromhex('41995C29'))[0] 19.170000076293945 >>> struct.unpack('!f', bytes.fromhex('470FC614'))[0] 36806.078125 

In Python 2:

>>> import struct >>> struct.unpack('!f', '41973333'.decode('hex'))[0] 18.899999618530273 >>> struct.unpack('!f', '41995C29'.decode('hex'))[0] 19.170000076293945 >>> struct.unpack('!f', '470FC614'.decode('hex'))[0] 36806.078125 
like image 163
Denis Otkidach Avatar answered Oct 03 '22 05:10

Denis Otkidach