Created
June 28, 2012 13:50
-
-
Save cwoodall/3011503 to your computer and use it in GitHub Desktop.
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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