MCPcopy Create free account
hub / github.com/ActiveState/code / nBitArray

Class nBitArray

recipes/Python/580649_nbitarray/recipe-580649.py:1–110  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class nBitArray() :
2
3 m = 32
4 f = 'I'
5
6 _default_type = None
7
8 def __init__(self, n_bit) :
9
10 if not (isinstance(n_bit, int) and n_bit > 0) :
11 raise ValueError
12
13 self.n_bit = n_bit
14 self.n_item = 0
15
16 self.b_mask = (2 ** self.n_bit) - 1
17 self.i_mask = ((0x1 << self.m) - 1)
18
19 def _normalize_index(self, index) :
20 if (-1 * self.n_item) <= index < 0 :
21 index += self.n_item
22 if 0 <= index < self.n_item :
23 return index
24 raise IndexError
25
26 def __getitem__(self, index):
27 if isinstance(index, int) :
28 return self._get_at(self._normalize_index(index))
29 elif isinstance(index, slice) :
30 return (self._get_at(i) for i in range(* index.indices(self.n_item)))
31 else:
32 raise TypeError("index must be int or slice")
33
34 def __str__(self) :
35 u = io.StringIO()
36 for n, i in enumerate(self._data) :
37 u.write("{0:08X}".format(i))
38 u.write('\n' if (n + 1) % 6 == 0 else ' ')
39 return u.getvalue()
40
41 def load_data(self, value_lst) :
42 """ load a list of n_bit words """
43 w_curs = 0 # position in the word
44 word = 0
45 stack = list()
46 for n, value in enumerate(value_lst) :
47 value = value & self.b_mask
48 v_curs = 0 # position in the value
49 v_count = self.n_bit - v_curs # number of remaining bits to be written
50 w_count = self.m - w_curs # number of bits available in the word
51 while v_count > 0 :
52 if w_count <= v_count :
53 p = value >> (v_count - w_count)
54 word |= p & self.i_mask
55 v_curs += w_count
56 w_curs += w_count
57 else :
58 p = value << (w_count - v_count)
59 word |= p & self.i_mask
60 v_curs += v_count

Callers 1

doFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected