Created
August 6, 2008 01:51
-
-
Save ishikawa/4152 to your computer and use it in GitHub Desktop.
Immutable Bit Array for Python
This file contains hidden or 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
| #!/usr/bin/env python | |
| import math | |
| import array | |
| class BitArray(object): | |
| """ | |
| A bit array (or bitmap, in some cases) is an array data structure which | |
| compactly stores individual bits (0 or 1). | |
| >>> b = BitArray(16) | |
| >>> len(b) | |
| 16 | |
| >>> b.bytes_length | |
| 2 | |
| >>> b[3] | |
| 0 | |
| >>> b[2] = 1 | |
| >>> b[2] | |
| 1 | |
| >>> b[5] = 1 | |
| >>> b[5] | |
| 1 | |
| >>> b[5] = 0 | |
| >>> b[5] | |
| 0 | |
| >>> b[5] = 1 | |
| >>> print list(b) | |
| [0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] | |
| """ | |
| def __init__(self, length): | |
| self.__length = length | |
| self.__bytes = array.array('B', "\x00" * int(math.ceil(length / 8.0))) | |
| @property | |
| def bytes_length(self): | |
| return len(self.__bytes) | |
| def __len__(self): | |
| return self.__length | |
| def __getitem__(self, i): | |
| assert isinstance(i, int) | |
| return int(self.__bytes[i>>3] & (1 << (i & 0x7)) > 0) | |
| def __setitem__(self, i, item): | |
| assert isinstance(i, int) | |
| if item is 0: | |
| self.__bytes[i>>3] &= ~(1 << (i & 0x7)) | |
| elif item is 1: | |
| self.__bytes[i>>3] |= (1 << (i & 0x7)) | |
| else: | |
| raise RuntimeError("item must be 0 or 1.") | |
| def __iter__(self): | |
| i = 0 | |
| while i < self.__length: | |
| yield self[i] | |
| i += 1 | |
| if __name__ == '__main__': | |
| import doctest | |
| doctest.testmod(verbose=False) |
This file contains hidden or 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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment