-1

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.

MShakeG
  • 391
  • 7
  • 45
  • I don't understand how your integer became the decimal number 100.00 ? – aSaffary Jan 16 '22 at 10:12
  • 1
    @aSaffary look into how fixed point numbers work, here's an online converter, enter 64 for Q and 100.00 for the floating point number and you'll see: https://www.rfwireless-world.com/calculators/floating-vs-fixed-point-converter.html – MShakeG Jan 16 '22 at 10:19

3 Answers3

2

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
Bharel
  • 23,672
  • 5
  • 40
  • 80
0

A different option is to use fractions, which will offer full precision as well:

>>> import fractions
>>> fractions.Fraction(1844674407370955161600, 1<<64)
Fraction(100, 1)
Bharel
  • 23,672
  • 5
  • 40
  • 80
0

In a general way, you can use fxpmath module to convert a Qm.n fixed-point type:

from fxpmath import Fxp

x_fxp = Fxp(1844674407370955161600, dtype='Q64.64', raw=True) # a fixed-point object

x_float = x_fxp.get_val() # or just x_fxp()

100.0

If you want a more short code:

x = Fxp(1844674407370955161600, dtype='Q64.64', raw=True)()
francof2a
  • 154
  • 4