Search code examples
pythonendianness

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?


Solution

  • 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