Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 544
Harry Lime Avatar asked Jan 30 '26 15:01

Harry Lime


1 Answers

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,)
like image 172
Martijn Pieters Avatar answered Feb 02 '26 06:02

Martijn Pieters