简体   繁体   中英

How to convert a hex-string into an unpacked IEEE 754 format number:-

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 ?

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,)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM