| 15 | int_types = (int, long) |
| 16 | |
| 17 | class BitArray(object): |
| 18 | def __init__(self, size, bits): |
| 19 | self.size = size |
| 20 | if len(bits) > size: |
| 21 | raise ValueError("size > len(bits)") |
| 22 | |
| 23 | bits_list = [] |
| 24 | for bit in bits: |
| 25 | x = int(bit) |
| 26 | if x not in [0, 1]: |
| 27 | raise ValueError("Not expected bits value {0}".format(x)) |
| 28 | bits_list.append(x) |
| 29 | |
| 30 | self.array = bits_list |
| 31 | if size > len(self.array): |
| 32 | self.array = ([0] * (size - len(self.array))) + self.array |
| 33 | |
| 34 | def dump(self): |
| 35 | res = [] |
| 36 | for i in range(self.size // 8): |
| 37 | c = 0 |
| 38 | for x in (self.array[i * 8: (i + 1) * 8]): |
| 39 | c = (c << 1) + x |
| 40 | res.append(c) |
| 41 | return bytearray((res)) |
| 42 | |
| 43 | def __getitem__(self, slice): |
| 44 | return self.array[slice] |
| 45 | |
| 46 | def __setitem__(self, slice, value): |
| 47 | self.array[slice] = value |
| 48 | return True |
| 49 | |
| 50 | def __repr__(self): |
| 51 | return repr(self.array) |
| 52 | |
| 53 | def __add__(self, other): |
| 54 | if not isinstance(other, BitArray): |
| 55 | return NotImplemented |
| 56 | return BitArray(self.size + other.size, self.array + other.array) |
| 57 | |
| 58 | def __or__(self, other): |
| 59 | if not isinstance(other, BitArray): |
| 60 | return NotImplemented |
| 61 | if self.size != other.size: |
| 62 | raise ValueError("OR ON DIFF SIZE") |
| 63 | new_array = [(x | y) for x, y in zip(self.array, other.array)] |
| 64 | return BitArray(self.size, new_array) |
| 65 | |
| 66 | def to_int(self): |
| 67 | return int("".join([str(i) for i in self.array]), 2) |
| 68 | |
| 69 | @classmethod |
| 70 | def from_string(cls, str_base): |
| 71 | l = [] |
| 72 | for c in bytearray(reversed(str_base)): |
| 73 | for i in range(8): |
| 74 | l.append(c & 1) |
no outgoing calls
no test coverage detected