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.
 

58 lines
1.6 KiB

import sys
class SBA:
slots = ('_arr', '_size', '_memsize')
def __init__(self, size):
if not isinstance(size, int):
raise ValueError("Size should be integer!")
self._arr = 1<<size
self._size = size
self._memsize = f"{round(sys.getsizeof(self._arr) / 1024, 2)} KByte"
@property
def memsize(self):
return self._memsize
def __getitem__(self, sliced):
if not isinstance(sliced, int):
raise ValueError("Only integers accepted as position!")
if sliced >= self._size:
raise ValueError("Range out of boundaries!")
if (self._arr & 1<<sliced) > 0:
return 1
return 0
def __setitem__(self, sliced, val):
if not isinstance(sliced, int):
raise ValueError("Only integers accepted as position!")
if not isinstance(val, (int, bool)):
raise ValueError("Values accepted as int or bool")
if sliced >= self._size:
raise ValueError("Range out of boundaries!")
if isinstance(val, bool):
v = {True: 1, False: 0}[val]
else:
if 0 > val > 1:
raise ValueError("Value is out of range!")
v = val
self._arr = self._arr | v<<sliced
def __len__(self):
return self._size
def to01(self):
return "".join([str(self.__getitem__(x)) for x in range(self._size-1, -1, -1)])
if __name__ == "__main__":
s = SBA(16)
print(s[1])
s[1] = 1
print(s[1])
print(len(s))
try:
print(s[16])
except Exception as e:
print(e)
print(s.to01())