Last active
December 2, 2020 13:53
-
-
Save gpiffault/13eb49288a9b029b25d84490a89ce041 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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