47 lines
1.1 KiB
Python
47 lines
1.1 KiB
Python
"""The Bits class makes bit level operations easier to write.
|
|
(c) 2020 S Groesz
|
|
"""
|
|
|
|
class Bits:
|
|
def __init__(self, data=None):
|
|
if data is None:
|
|
self.__raw = b''
|
|
else:
|
|
self.__raw = bytes(data)
|
|
|
|
def __bytes__(self):
|
|
return self.__raw
|
|
|
|
def __int__(self):
|
|
#return int.from_bytes(bytes(self), "big") # alternative Py > 3.1
|
|
i = 0
|
|
for b in bytes(self):
|
|
i = i * 256 + int(b) # Python 2: int(b) -> ord(b)
|
|
return i
|
|
|
|
def __hash__(self):
|
|
return hash(bytes(self))
|
|
|
|
def __repr__(self):
|
|
return (f'{self.__class__.__name__}({bytes(self)})')
|
|
#return "{:08b}".format(int(self))
|
|
|
|
def __eq__(self, compare):
|
|
return hash(self) == hash(compare)
|
|
|
|
def __ne__(self, compare):
|
|
return hash(self) != hash(compare)
|
|
|
|
def __lt__(self, compare):
|
|
return int(self) < int(compare)
|
|
|
|
def __le__(self, compare):
|
|
return int(self) <= int(compare)
|
|
|
|
def __gt__(self, compare):
|
|
return int(self) > int(compare)
|
|
|
|
def __ge__(self, compare):
|
|
return int(self) >= int(compare)
|
|
|