How to convert the following hex string to float (single precision 32-bit) in Python?
"41973333" -> 1.88999996185302734375E1 "41995C29" -> 1.91700000762939453125E1 "470FC614" -> 3.6806078125E4
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.
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.
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
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