Advertisement
silver2row

bitwise?

Feb 5th, 2023
869
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. # Some site online: https://www.digitalocean.com/community/tutorials/python-bitwise-operators
  4.  
  5. class Data:
  6.     id = 2
  7.  
  8.     def __init__(self, i):
  9.         self.id = i
  10.  
  11.     def __and__(self, other):
  12.         print('Bitwise AND operator overloaded')
  13.         if isinstance(other, Data):
  14.             return Data(self.id & other.id)
  15.         else:
  16.             raise ValueError('Argument must be object of Data')
  17.  
  18.     def __or__(self, other):
  19.         print('Bitwise OR operator overloaded')
  20.         if isinstance(other, Data):
  21.             return Data(self.id | other.id)
  22.         else:
  23.             raise ValueError('Argument must be object of Data')
  24.  
  25.     def __xor__(self, other):
  26.         print('Bitwise XOR operator overloaded')
  27.         if isinstance(other, Data):
  28.             return Data(self.id ^ other.id)
  29.         else:
  30.             raise ValueError('Argument must be object of Data')
  31.  
  32.     def __lshift__(self, other):
  33.         print('Bitwise Left Shift operator overloaded')
  34.         if isinstance(other, int):
  35.             return Data(self.id << other)
  36.         else:
  37.             raise ValueError('Argument must be integer')
  38.  
  39.     def __rshift__(self, other):
  40.         print('Bitwise Right Shift operator overloaded')
  41.         if isinstance(other, int):
  42.             return Data(self.id >> other)
  43.         else:
  44.             raise ValueError('Argument must be integer')
  45.  
  46.     def __invert__(self):
  47.         print('Bitwise Ones Complement operator overloaded')
  48.         return Data(~self.id)
  49.  
  50.     def __str__(self):
  51.         return f'Data[{self.id}]'
  52.  
  53.  
  54. d1 = Data(10)
  55. d2 = Data(5)
  56.  
  57. print(f'd1&d2 = {d1&d2}')
  58. print(f'd1|d2 = {d1|d2}')
  59. print(f'd1^d2 = {d1^d2}')
  60. print(f'd1<<2 = {d1<<2}')
  61. print(f'd1>>2 = {d1>>2}')
  62. print(f'~d1 = {~d1}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement