Harry Boy
Harry Boy

Reputation: 4777

Convert hex string to float in little endian format

I am converting a hex string which I know is in little endian format as follows to float.

hex_string = '00e0b8bf'
to_int = int(hex_string, 16)
struct_packed = struct.pack(">i", to_int)
to_float = struct.unpack(">f", struct_packed)[0]

How can I convert hex_string to little endian format?

Upvotes: 1

Views: 806

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 178001

You can use bytes.fromhex to get a byte representation of the hex value, then unpack using < for little-endian format:

>>> x = '00e0b8bf'
>>> bytes.fromhex(x)
b'\x00\xe0\xb8\xbf'
>>> import struct
>>> struct.unpack('<f',bytes.fromhex(x))[0]
-1.4443359375

Upvotes: 3

Related Questions