|
5 | 5 |
|
6 | 6 | classBit:
|
7 | 7 | def__init__(self,value):
|
8 |
| -ifisinstance(value,str): |
9 |
| -self._value=self.from_text(value)._value |
10 |
| -elifisinstance(value,bytes): |
11 |
| -self._value=np.unpackbits(np.frombuffer(value,dtype=np.uint8)).astype(bool) |
| 8 | +ifisinstance(value,bytes): |
| 9 | +self._len=8*len(value) |
| 10 | +self._data=value |
12 | 11 | else:
|
13 |
| -value=np.asarray(value) |
| 12 | +ifisinstance(value,str): |
| 13 | +value= [v!='0'forvinvalue] |
| 14 | +else: |
| 15 | +value=np.asarray(value) |
14 | 16 |
|
15 |
| -ifvalue.dtype!=np.bool: |
16 |
| -warn('expected elements to be boolean',stacklevel=2) |
17 |
| -value=value.astype(bool) |
| 17 | +ifvalue.dtype!=np.bool: |
| 18 | +warn('expected elements to be boolean',stacklevel=2) |
| 19 | +value=value.astype(bool) |
18 | 20 |
|
19 |
| -ifvalue.ndim!=1: |
20 |
| -raiseValueError('expected ndim to be 1') |
| 21 | +ifvalue.ndim!=1: |
| 22 | +raiseValueError('expected ndim to be 1') |
21 | 23 |
|
22 |
| -self._value=value |
| 24 | +self._len=len(value) |
| 25 | +self._data=np.packbits(value).tobytes() |
23 | 26 |
|
24 | 27 | def__repr__(self):
|
25 | 28 | returnf'Bit({self.to_text()})'
|
26 | 29 |
|
27 | 30 | def__eq__(self,other):
|
28 | 31 | ifisinstance(other,self.__class__):
|
29 |
| -returnnp.array_equal(self.to_numpy(),other.to_numpy()) |
| 32 | +returnself._len==other._lenandself._data==other._data |
30 | 33 | returnFalse
|
31 | 34 |
|
32 | 35 | defto_list(self):
|
33 |
| -returnself._value.tolist() |
| 36 | +returnself.to_numpy().tolist() |
34 | 37 |
|
35 | 38 | defto_numpy(self):
|
36 |
| -returnself._value |
| 39 | +returnnp.unpackbits(np.frombuffer(self._data,dtype=np.uint8),count=self._len).astype(bool) |
37 | 40 |
|
38 | 41 | defto_text(self):
|
39 |
| -return''.join(self._value.astype(np.uint8).astype(str)) |
| 42 | +return''.join(format(v,'08b')forvinself._data)[:self._len] |
40 | 43 |
|
41 | 44 | defto_binary(self):
|
42 |
| -returnpack('>i',len(self._value))+np.packbits(self._value).tobytes() |
| 45 | +returnpack('>i',self._len)+self._data |
43 | 46 |
|
44 | 47 | @classmethod
|
45 | 48 | deffrom_text(cls,value):
|
46 |
| -returncls(np.asarray([v!='0'forvinvalue],dtype=bool)) |
| 49 | +returncls(str(value)) |
47 | 50 |
|
48 | 51 | @classmethod
|
49 | 52 | deffrom_binary(cls,value):
|
50 |
| -count=unpack_from('>i',value)[0] |
51 |
| -buf=np.frombuffer(value,dtype=np.uint8,offset=4) |
52 |
| -returncls(np.unpackbits(buf,count=count).astype(bool)) |
| 53 | +ifnotisinstance(value,bytes): |
| 54 | +raiseValueError('expected bytes') |
| 55 | + |
| 56 | +bit=cls.__new__(cls) |
| 57 | +bit._len=unpack_from('>i',value)[0] |
| 58 | +bit._data=value[4:] |
| 59 | +returnbit |
53 | 60 |
|
54 | 61 | @classmethod
|
55 | 62 | def_to_db(cls,value):
|
|