Representing floats as a series of hex values

4 thoughts on “Representing floats as a series of hex values

  1. Does anyone have any ideas on how to represent a float value as 4 hexadecimal values when the struct module is unavailable? In C you would just cast a float* to an uint8_t* and iterate over the 4 bytes but I cannot figure out how to concatenate them back to a float in Python.

      1. 3.14 is represented as 0x4048f5c3 or [0x40 0x48, 0xf5, 0xc3] when using IEEE754 floating point notation. This can easily be sent as 4 bytes from a C program and then decoded back to a float using the python struct module:

        >>> struct.unpack('>f', 'x40x48xf5xc3')


        However, since the Telit interpreter lacks this module it becomes trickier. Anyway, I rolled my own decoder which turned out to be fairly trivial. A bit slow, perhaps:

        def get_float(data):


            Extracts a float value encoded as IEEE 754 single point precision.


            @param data: List to read data from.

            @return: Data converted to a single precision floating point value.


            int_val = get_uint32(data)


            SIGN_MASK = 0x80000000

            EXP_MASK = 0x7F800000

            FRAC_MASK = 0x7FFFFF


            # Extract sign, the most significant bit

            negative = int_val & SIGN_MASK

            # Extract exponent

            exp = ((int_val & EXP_MASK) >> 23) - 127

            # Calculate significand

            sig = 0x800000 | (int_val & FRAC_MASK)

            sig = float(sig) / 0x800000


            # Calculate final float value.

            val = sig * (2 ** exp)

            return -val if negative else val