Skip to content

Instantly share code, notes, and snippets.

@laerreal
Created March 25, 2019 22:49
Show Gist options
  • Save laerreal/232b2ab90eabeb24e10e62b971eb9ffd to your computer and use it in GitHub Desktop.
Save laerreal/232b2ab90eabeb24e10e62b971eb9ffd to your computer and use it in GitHub Desktop.
def cast(v):
if isinstance(v, bitmap):
return v.i
else:
return v
class bitmap(object):
__slots__ = ("i",)
def __init__(self, i = 0):
self.i = i
@property
def bits(self):
i = self.i
while i:
yield i & 1
i >>= 1
def __iter__(self):
for i, bit in enumerate(self.bits):
if bit:
yield i
def __setitem__(self, n, bit):
if bit:
self.i |= 1 << n
else:
low_mask = (1 << n) - 1
i = self.i
n += 1
high = i >> n << n
self.i = high | i & low_mask
def __str__(self):
res = ""
for b in self.bits:
res = ("1" if b else "0") + res
if not res:
res = "0"
return res
def __and__(self, v):
return bitmap(self.i & cast(v))
b = bitmap(0xAA)
def p():
global b
print(list(b))
print(b)
p()
b[20] = 1
p()
b[6] = 1
p()
b[8] = 1
p()
b[7] = 0
p()
b[80] = 1
p()
b[200] = 1
p()
b = b & 3
p()
b = b & bitmap(3)
p()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment