You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
907 B

6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
6 months ago
  1. class Byte:
  2. def __init__(self, value: int):
  3. self.value = value
  4. def set_bit(self, bitnr: int, val: bool):
  5. chain1 = (1 << bitnr)
  6. chain2 = ~chain1
  7. if val == 1:
  8. self.value |= chain1
  9. else:
  10. self.value &= chain2
  11. def is_set(self, bitnr: int):
  12. return (self.value >> bitnr) & 1
  13. def toggle_bit(self, bitnr: int):
  14. self.value = (self.value ^ (1 << bitnr))
  15. def swap_bit(self,bitnr1: int, bitnr2: int):
  16. b1 = (self.value >> bitnr1) & 0b1
  17. b2 = (self.value >> bitnr2) & 0b1
  18. self.value &= ~(1 << bitnr1)
  19. self.value |= b2 << bitnr1
  20. self.value &= ~(1 << bitnr2)
  21. self.value |= b1 << bitnr2
  22. def __str__(self):
  23. return bin(self.value)[2:]
  24. def __int__(self):
  25. return self.value
  26. def __and__(self, other):
  27. return Byte(int(self) & int(other))
  28. def __or__(self, other):
  29. return Byte(int(self) | int(other))
  30. def __xor__(self, other):
  31. return Byte(int(self) ^ int(other))