Skip to content

Instantly share code, notes, and snippets.

@tinybike
Created July 9, 2016 01:38
Show Gist options
  • Select an option

  • Save tinybike/4e57d4dc30525f06293394c3dcd02a51 to your computer and use it in GitHub Desktop.

Select an option

Save tinybike/4e57d4dc30525f06293394c3dcd02a51 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
from decimal import *
base_binary = Decimal(2)**Decimal(64)
base_decimal = Decimal(10)**Decimal(20)
def fix_binary(n):
return Decimal(n) * base_binary
def unfix_binary(n):
return Decimal(n) / base_binary
def fix_decimal(n):
return Decimal(n) * base_decimal
def unfix_decimal(n):
return Decimal(n) / base_decimal
n = "1.2"
fxp_binary = fix_binary(n)
hex_fxp_binary = hex(int(fxp_binary))
print "Base 2^64 fixed-point:"
print fxp_binary
print (len(hex_fxp_binary) - 3) / 2, hex_fxp_binary
print unfix_binary(int(fxp_binary))
fxp_decimal = fix_decimal(n)
hex_fxp_decimal = hex(int(fxp_decimal))
print "Base 10^20 fixed-point:"
print fxp_decimal
print (len(hex_fxp_decimal) - 3) / 2, hex_fxp_decimal
print unfix_decimal(int(fxp_decimal))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment