Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # The Bit class.
- class Bit:
- '''A single bit class.
- All of the operations: "invert/not", "or", "and" and "full_adder" are built directly or indirectly on "nor".
- '''
- def __init__(self, a_val):
- '''Instantiate the Bit object with any valid inputs'''
- if a_val not in [0, 1, 4, 5]:
- raise ValueError
- self.val = a_val
- def nor(self, b):
- ''' Return a NOR b.
- Yes I could have written this in one line but this version doesn't use any binary logical operators.
- '''
- if self:
- return ZERO
- elif b:
- return ZERO
- else:
- return ONE
- def __str__(self):
- return str(self.val)
- def __bool__(self):
- ''' True if it is 4 or 5; False if it is 0 or 1. '''
- if self.val > 3:
- return True
- elif self.val < 2:
- return False
- def __invert__(self):
- ''' Return the NOT of self. Built on NOR.
- '''
- return self.nor(self)
- def __or__(self, b):
- ''' Return self OR b.
- Built on NOR and NOT. '''
- return ~self.nor(b)
- def __and__(self, b):
- ''' Return self AND b.
- Built on NOT and OR using DeMorgan's law. '''
- return ~(~self | ~b)
- def full_adder(self, b):
- ''' Return self + b + carry as a single bit with carry set as well. Built on AND, OR and NOT.
- See Figure 3.15 in the textbook.
- '''
- global carry # it is processor global status
- bitsum = (((self|b)&~(self&b))|carry)&~(((self|b)&~(self&b))&carry)
- carry = (self & b) | (self & carry) | (b & carry)
- return carry
- ZERO = Bit(0) # or Bit(1)
- ONE = Bit(4)
- carry = ZERO
- c = Bit(4)
- d = Bit(5)
- e = Bit(5)
- f = Bit(5)
- print(c.full_adder(d))
- print(carry)
- print(e.full_adder(f))
- print(carry)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement