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