Mercurial > lcfOS
comparison python/ppci/target/token.py @ 342:86b02c98a717 devel
Moved target directory
author | Windel Bouwman |
---|---|
date | Sat, 01 Mar 2014 15:40:31 +0100 |
parents | |
children | 988f3fb861e4 |
comparison
equal
deleted
inserted
replaced
341:4d204f6f7d4e | 342:86b02c98a717 |
---|---|
1 | |
2 import struct | |
3 | |
4 def u16(h): | |
5 return struct.pack('<H', h) | |
6 | |
7 | |
8 def u32(x): | |
9 return struct.pack('<I', x) | |
10 | |
11 | |
12 def val2bit(v, bits): | |
13 b = [] | |
14 for i in range(bits): | |
15 b.append(bool((1<<i) & v)) | |
16 #b.reverse() | |
17 return b | |
18 | |
19 | |
20 def bit_range(b, e): | |
21 """ Property generator function """ | |
22 getter = lambda s: s[b:e] | |
23 def setter(s, v): | |
24 s[b:e] = v | |
25 return property(getter, setter) | |
26 | |
27 | |
28 class Token: | |
29 def __init__(self, bitsize): | |
30 self.bitsize = bitsize | |
31 self.bit_value = 0 | |
32 | |
33 def set_bit(self, i, value): | |
34 value = bool(value) | |
35 assert i in range(0, self.bitsize) | |
36 mask = 1 << i | |
37 if value: | |
38 self.bit_value |= mask | |
39 else: | |
40 self.bit_value &= (~mask) | |
41 | |
42 def __getitem__(self, key): | |
43 return False | |
44 | |
45 def __setitem__(self, key, value): | |
46 if type(key) is int: | |
47 self.set_bit(key, value) | |
48 elif type(key) is slice: | |
49 assert key.step is None | |
50 bits = key.stop - key.start | |
51 value_bits = val2bit(value, bits) | |
52 for i in range(key.start, key.stop): | |
53 self.set_bit(i, value_bits[i - key.start]) | |
54 else: | |
55 raise KeyError() | |
56 |