Search code examples
pythonbit-manipulationfixed-point

How to Convert Fixed Point Number to Decimal Number in Python?


How do I convert a signed 64.64-bit fixed point integer to a decimal number in python?

For example the integer 1844674407370955161600 which is a signed 64.64-bit fixed point represents the decimal number +100.00, my understanding is that a python float has insufficient bits(only 18) to represent the fractional part, hence my choice of the decimal type.

Perhaps a more general function for converting Qm.n to a decimal can be provided.


Solution

  • You can use decimal.Decimal and divide by the fixed point like so:

    >>> import decimal
    >>> decimal.Decimal(1844674407370955161600) / (1 << 64)
    Decimal('100')
    

    Keep in mind you'll need at least 39 digits for full precision. Make sure you set it before you start converting:

    >>> decimal.getcontext().prec = 39