Skip to content

Instantly share code, notes, and snippets.

@evertheylen
Created December 19, 2014 20:40
Show Gist options
  • Save evertheylen/c11830e4003c979a1b58 to your computer and use it in GitHub Desktop.
Save evertheylen/c11830e4003c979a1b58 to your computer and use it in GitHub Desktop.
import math
defaultbits = 8
def char_to_int(s):
return int(s, 36)
def int_to_char(i):
if 0 <= i <= 9:
return str(i)
elif 10 <= i <= 36:
return chr(ord('a') + i - 10)
else:
print("error trying to convert", i, "to a character.")
return " <x> "
def invert_bitstring(s):
inverted = ""
for char in s:
if char == "0": inverted += "1"
else: inverted += "0" # interpreting every character but "0" as a "1"
return inverted
def Radix(base):
class Number:
def base(self):
return base
def __init__(self, value):
self.val = 0
if type(value) == str:
self.from_string(value)
elif type(value) == int:
self.val = value
else:
self.val = value.val
def from_string(self, s):
self.val = int(s, base)
def to_string(self, minlength = 0):
s = ""
sign = ""
value = self.val
if self < 0:
sign = "-"
value = abs(self.val)
remainders = []
while value != 0:
remainders.append(int_to_char(value % base))
value = value // base
# inverting the remainders
s += "".join(remainders[::-1])
return sign + "0"*max(minlength-len(s), 0) + s
def __lt__(self, other):
if int(self) < int(other):
return True
return False
def __le__(self, other):
if int(self) <= int(other):
return True
return False
def __eq__(self, other):
if int(self) == int(other):
return True
return False
def __int__(self):
return self.val
def __str__(self):
return self.to_string()
def __repr__(self):
return self.to_string()
return Number
Bin = Radix(2)
Oct = Radix(8)
Hex = Radix(16)
class TwoCom(Bin):
def __init__(self, value, length = defaultbits):
self.val = 0
if type(value) == str:
self.from_string(value)
self.length = len(value)
elif type(value) == int:
self.val = value
self.length = length
else:
self.val = value.val
self.length = length
def from_string(self, s):
if s[0] == "1":
self.val = -(int(Bin(invert_bitstring(s)))+1)
else:
self.val = Bin(s).val
def to_string(self):
# length is the fixed this time!
if not -(2**self.length-1) <= self.val <= (2**self.length-1)-1:
print("Not enough bits. A better choice would be",math.ceil(math.log(abs(self.val), 2)),"instead of",self.length)
return "----"
s = ""
if self.val < 0:
s = "1" + invert_bitstring(Bin(abs(self.val)-1).to_string(self.length-1))
else:
s = "0" + Bin(self.val).to_string(self.length-1)
return s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment