Skip to content

Commit 6e81a51

Browse files
committed
Cleanup comments
Few typos, debugging advice
1 parent 82695f8 commit 6e81a51

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

bit_manipulation/multibit_manipulation.py

+12-9
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
just three parts: left-hand side, value, right-hand side.
3232
3333
For example, say you want to insert two ones in the middle of 0b101101,
34-
that is -> 0b10111101. Index is 2 ( 0 ,1, 2 from the right ) and the
34+
that is -> 0b10111101. Index is 3 ( 0 ,1, 2, 3 from the right ) and the
3535
value is 3 (0b11) with a bit length of 2.
3636
3737
- Shift >> index right to produce 0b101
@@ -44,15 +44,21 @@
4444
-> 0b10111101.
4545
4646
To remove the center two bits of 0b101101 -> 0b1001, the process is mostly
47-
the same.
47+
the same. Index is 2 for the remove operation on the right-center bit
48+
rather than 3 for inserting, because we are referring to the bit itself
49+
rather the position to the right of the bit index.
4850
49-
- The initial right shift is index(2) + bit_length(2), taking out the two
51+
- The initial right shift is index (2 ) + bit_length(2), taking out the two
5052
middle bits and producing 0b10.
5153
- The left shift of index produces 0b1000.
5254
- The original bint is ANDed with bitmask 0b11 producing 0b01 which is
5355
ORed with 0b1000 yielding the target 0b1001.
5456
55-
It's not so bad once you get the hang of it.
57+
It's not so bad once you get the hang of it, although it can still be a
58+
bear to debug. In the insert example above, the result of inserting 0b11
59+
in the center ( index=3 ) or to the right ( index=2 ) produces the same
60+
correct result despite the misspecification. These algorithms are very
61+
fast but can be touchy at times.
5662
5763
Various bit insert/remove solutions exist using bin() string functions
5864
and slicing, but this bitwise implementation is significantly faster
@@ -64,10 +70,6 @@
6470

6571
bit_length = int.bit_length
6672

67-
"""The only consistent error checking is for bint < 0 or index < 0 etc.,
68-
and for bit_length(value) > bit_len, which can cause silent errors.
69-
Anything like int(None) is going to cause a loud error. """
70-
7173

7274
def bit_get(bint: int, index: int) -> int:
7375
"""Get value of bit at index in bint.
@@ -197,7 +199,7 @@ def multibit_set(bint: int, index: int, bit_len: int, value: int) -> int:
197199

198200

199201
def multibit_insert(bint: int, index: int, bit_len: int, value: int) -> int:
200-
"""Insert before index-th slot
202+
"""Insert value before index-th slot
201203
202204
>>> multibit_insert(0, 1, 1, 1)
203205
2
@@ -245,6 +247,7 @@ def multibit_remove(bint: int, index: int, bit_len: int) -> int:
245247

246248

247249
if __name__ == "__main__":
250+
248251
import doctest
249252

250253
doctest.testmod()

0 commit comments

Comments
 (0)