Reputation: 2217
using Python 2.7.3: How to convert a hex-string into an unpacked IEEE 754 format number:-
I have a string of hex data in this form:
data = '38 1A A3 44'
I would like to convert this to a floating point number by using struct.unpack:
fdata = struct.unpack('<f','\x38\xA1\xA3\x44') # fdata=1304.8193359375
Is there a Pythonic solution or do I need to somehow substitute an escape sequence for each space in data?
Upvotes: 3
Views: 9795
Reputation: 1122252
Convert the hex codepoints to a byte string first; binascii.unhexlify()
can do this for you, provided you remove the whitespace:
import binascii
import struct
fdata = struct.unpack('<f', binascii.unhexlify(data.replace(' ', '')))[0]
Demo:
>>> import binascii
>>> import struct
>>> data = '38 1A A3 44'
>>> struct.unpack('<f', binascii.unhexlify(data.replace(' ', '')))
(1304.8193359375,)
Upvotes: 7