Skip to content

Instantly share code, notes, and snippets.

@gpiffault
Last active December 2, 2020 13:53
Show Gist options
  • Save gpiffault/13eb49288a9b029b25d84490a89ce041 to your computer and use it in GitHub Desktop.
Save gpiffault/13eb49288a9b029b25d84490a89ce041 to your computer and use it in GitHub Desktop.
import math
class Bitfield:
def __init__(self, size):
self.size = size
self.bytes = bytearray(math.ceil(size / 8))
def __len__(self):
return self.size
def __getitem__(self, idx):
return self.bytes[idx // 8] >> (idx % 8) & 1
def __setitem__(self, idx, value):
mask = 1 << (idx % 8)
if value:
self.bytes[idx // 8] |= mask
else:
self.bytes[idx // 8] &= ~mask
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment