pythonwise / bits.py

 ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79``` ```def mask(size): '''Mask for `size' bits >>> mask(3) 7 ''' return (1L << size) - 1 def num2bits(num, width=32): '''String represntation (in bits) of a number >>> num2bits(3, 5) '00011' ''' s = "" for bit in range(width - 1, -1, -1): if num & (1L << bit): s += "1" else: s += "0" return s def get_bit(value, bit): '''Get value of bit >>> num2bits(5, 5) '00101' >>> get_bit(5, 0) 1 >>> get_bit(5, 1) 0 ''' return (value >> bit) & 1 def get_range(value, start, end): '''Get range of bits >>> num2bits(5, 5) '00101' >>> get_range(5, 0, 1) 1 >>> get_range(5, 1, 2) 2 ''' return (value >> start) & mask(end - start + 1) def set_bit(num, bit, value): '''Set bit `bit' in num to `value' >>> i = 5 >>> set_bit(i, 1, 1) 7 >>> set_bit(i, 0, 0) 4 ''' if value: return num | (1L << bit) else: return num & (~(1L << bit)) def sign_extend(num, size): '''Sign exten number who is `size' bits wide >>> sign_extend(5, 2) 1 >>> sign_extend(5, 3) -3 ''' m = mask(size - 1) res = num & m # Positive if (num & (1L << (size - 1))) == 0: return res # Negative, 2's complement res = ~res res &= m res += 1 return -res ```
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.