Search code examples
pythonfixed-point

Reinterpret uint16 as fixed-point with 14 fractional bits in Python


I am sending data (signed 16bit fixed-point with 14 fractional bits) from one system to another. Due to constraints, the data has to be reinterpreted as uint16 before it is transmitted (i.e. bit representation is the same). The data ends up in Python but I am struggling to find a method to reinterpret this back to its original form.

For example: The original value is -0.123, reinterpreted as uint16 with value 63521.

How do I convert this back to the value -0.123 using Python?

Some More Examples

1.0450  -> 17121
0.9870  -> 16171
-0.9870 -> 49365

Solution

  • A possible way to convert it back is:

    def Q2_14toFloat(x):
        # convert unsigned to signed
        x = (x ^ 0x8000) - 0x8000
        # scale
        return x * (1.0 / 16384.0)