Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Unsigned Fixed Point... With a little bit of work can work for signed, will convert to signed for large numbers if you try to convert to float or string... Not much interest in fixing, because it works for my little 16 bit numbers (and masks down to your
class UFixedPoint(object):
def __init__(self, num, m, n):
self.mask = 2**(m + n) - 1
self.k = (1 << (n - 1))
self.m = m
self.n = n
temp = int(num * 2**self.n)
self.value = temp & self.mask
def __add__(self, other):
# Currently only allow same Qm.n Floats
if (self.m == other.m) and (self.n == other.n):
temp = UFixedPoint(0, self.m, self.n)
temp.value = (self.value + other.value) & self.mask
return temp
else:
return 0
def __sub__(self, other):
if (self.m == other.m) and (self.n == other.n):
temp = UFixedPoint(0, self.m, self.n)
temp.value = (self.value - other.value) & self.mask
return temp
else:
return 0
def __mul__(self, other):
if (self.m == other.m) and (self.n == other.n):
temp = UFixedPoint(0, self.m, self.n)
temp.value = (self.value * other.value) + self.k
temp.value >>= self.n
return temp
else:
return 0
def __div__(self,other):
if (self.m == other.m) and (self.n == other.n):
temp = UFixedPoint(0, self.m, self.n)
temp.value = self.value << self.n
temp.value += (other.value >> 1)
temp.value = temp.value/other.value
return temp
else:
return 0
def __float__(self):
return (float(self.value) / (2**self.n))
def __str__(self):
return "%f" % float(self)
num = 1.5
num = UFixedPoint(num, 12, 4)
numb = UFixedPoint(440, 12, 4)
print numb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.