In Python the <<
operator does the following:
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.
I want to have another version where it fills 1
on the new bits. Is there a built in function for this, if not how do I write it?
Advertisement
Answer
Is x = (x << y) | ((1 << y) - 1)
what you’re looking for?
First, we shift x left y bits:
JavaScript
x
5
1
x = 21
2
y = 2
3
bin(x) == 10101 (in binary)
4
x << y == 1010100
5
Then, the number ((1 << y) – 1) gives us a number with only the y lowest bits set to 1, e.g.
JavaScript
1
3
1
1 << 2 == 100
2
(1 << 2) - 1 == 011
3
Finally, we or
them to get 1010100 | 11 == 1010111
.