Skip to content
Advertisement

Left shift but replace the shifted bits with ones

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:

x = 21
y = 2
bin(x) == 10101 (in binary)
x << y == 1010100

Then, the number ((1 << y) – 1) gives us a number with only the y lowest bits set to 1, e.g.

1 << 2 == 100
(1 << 2) - 1 == 011

Finally, we or them to get 1010100 | 11 == 1010111.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement