💬 Question: Given a hexadecimal string. How to convert it to a float?
Here are a few example conversions where each hex string represents four bytes, i.e., two hex characters per byte.
Solution – Convert Hex to Float
struct.unpack('!f', bytes.fromhex('12ff01ca')) converts a hexadecimal string
'12ff01ca' to a bytes object and then to a float using the specifier
'!f' of the
import struct print(struct.unpack('!f', bytes.fromhex('12ff01ca'))) # 7.053344520075142e-30
Let’s deconstruct this expression.
First, create a bytes object from the hex string:
>>> bytes.fromhex('12ff01ca') b'\x12\xff\x01\xca'
Second, pass it in the
>>> struct.unpack('!f', b'\x12\xff\x01\xca') (1.6093203504465906e-27,)
Third, get the first tuple value (the output of the
struct.unpack() function is always a tuple even if only one tuple value exists):
>>> (1.6093203504465906e-27,) 1.6093203504465906e-27
You can learn more about the specifications of the
struct library calls here:
👉 This module performs conversions between Python values and C structs represented as Python
Generally, the most important functions in the library are:
You provide the format of the data using specifiers like these:
?: boolean h: short l: long i: int f: float q: long long int
In our case, you only need the
'f' format specifier with the
'!' prefix. The format specifier
'!' represents the network byte order (big endian).
Convert Hex List to Float List
If you want to convert multiple hex strings in a list to a float list, you can use a simple
for loop like so:
import struct lst =  for i in ['4282cbf1', '43322ffb', '534f11ab', '0f0f0f0f']: lst.append(struct.unpack('!f', bytes.fromhex(i))) print(lst) # [65.39832305908203, 178.1874237060547, 889354649600.0, 7.053344520075142e-30]
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.