| 3 | # |
| 4 | |
| 5 | class bf(object): |
| 6 | def __init__(self,value=0): |
| 7 | "Init bitfield with a value int in bin, hex, oct or dec" |
| 8 | self._d = value |
| 9 | |
| 10 | def __getitem__(self, index): |
| 11 | "return bit value for that index (n-0)" |
| 12 | return (self._d >> index) & 1 |
| 13 | |
| 14 | def __setitem__(self,index,value): |
| 15 | "set bit value for that index (n-0)" |
| 16 | value = (value&1)<<index |
| 17 | mask = (1)<<index |
| 18 | self._d = (self._d & ~mask) | value |
| 19 | |
| 20 | def __getslice__(self, start, end): |
| 21 | "return bits slice from start to end (n-0)" |
| 22 | mask = 2**(end - start + 1) -1 |
| 23 | return ((self._d >> start) & mask) |
| 24 | |
| 25 | def __setslice__(self, start, end, value): |
| 26 | "set bits slice from start to end index (n-0) with the given value" |
| 27 | mask = 2**(end - start + 1) -1 |
| 28 | value = (value & mask) << start |
| 29 | mask = mask << start |
| 30 | self._d = (self._d & ~mask) | value |
| 31 | return (self._d >> start) & mask |
| 32 | |
| 33 | def __int__(self): |
| 34 | "add de int() function for bf" |
| 35 | return self._d |
| 36 | |
| 37 | def int(self): |
| 38 | "add the bf.int() function return int" |
| 39 | return self._d |
| 40 | |
| 41 | def bin(self): |
| 42 | "add the bf.bin() function return str" |
| 43 | return '{0:0b}'.format(self._d) |
| 44 | |
| 45 | def hex(self): |
| 46 | "add the bf.hex() function return str" |
| 47 | return '{0:0x}'.format(self._d) |
| 48 | |
| 49 | def __repr__(self): |
| 50 | "add the basic return function, return bin str" |
| 51 | return '{0:0b}'.format(self._d) |
| 52 | |
| 53 | def __len__(self): |
| 54 | "add the len() function return int with the bit number count" |
| 55 | return len('{0:0b}'.format(self._d)) |
| 56 | |
| 57 | def unpack(self,pack): |
| 58 | "return the unpack bit fields in dec [ n1, n2, n3...] with length given in pack [ l1, l2, l3...]" |
| 59 | r=[]; ss=0;pack.reverse() |
| 60 | for i in pack: |
| 61 | r.append(self.__getslice__(ss,ss+i-1)) |
| 62 | ss +=i |
no outgoing calls
no test coverage detected