Advertisement
Guest User

Untitled

a guest
Aug 23rd, 2017
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. # The Bit class.
  2. class Bit:
  3. '''A single bit class.
  4. All of the operations: "invert/not", "or", "and" and "full_adder" are built directly or indirectly on "nor".
  5. '''
  6.  
  7. def __init__(self, a_val):
  8. '''Instantiate the Bit object with any valid inputs'''
  9. if a_val not in [0, 1, 4, 5]:
  10. raise ValueError
  11. self.val = a_val
  12.  
  13. def nor(self, b):
  14. ''' Return a NOR b.
  15. Yes I could have written this in one line but this version doesn't use any binary logical operators.
  16. '''
  17. if self:
  18. return ZERO
  19. elif b:
  20. return ZERO
  21. else:
  22. return ONE
  23.  
  24. def __str__(self):
  25. return str(self.val)
  26.  
  27. def __bool__(self):
  28. ''' True if it is 4 or 5; False if it is 0 or 1. '''
  29. if self.val > 3:
  30. return True
  31. elif self.val < 2:
  32. return False
  33.  
  34. def __invert__(self):
  35. ''' Return the NOT of self. Built on NOR.
  36. '''
  37. return self.nor(self)
  38.  
  39.  
  40. def __or__(self, b):
  41. ''' Return self OR b.
  42. Built on NOR and NOT. '''
  43. return ~self.nor(b)
  44.  
  45.  
  46. def __and__(self, b):
  47. ''' Return self AND b.
  48. Built on NOT and OR using DeMorgan's law. '''
  49. return ~(~self | ~b)
  50.  
  51.  
  52. def full_adder(self, b):
  53. ''' Return self + b + carry as a single bit with carry set as well. Built on AND, OR and NOT.
  54. See Figure 3.15 in the textbook.
  55. '''
  56. global carry # it is processor global status
  57. bitsum = (((self|b)&~(self&b))|carry)&~(((self|b)&~(self&b))&carry)
  58. carry = (self & b) | (self & carry) | (b & carry)
  59. return carry
  60.  
  61.  
  62. ZERO = Bit(0) # or Bit(1)
  63. ONE = Bit(4)
  64. carry = ZERO
  65. c = Bit(4)
  66. d = Bit(5)
  67. e = Bit(5)
  68. f = Bit(5)
  69.  
  70. print(c.full_adder(d))
  71. print(carry)
  72. print(e.full_adder(f))
  73. print(carry)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement