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?
CodePudding user response:
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
.
CodePudding user response:
There's no such function built in, or, for that matter, available in any extension library I know of.
It's pretty easy to do yourself, though. Say the int is n
and you want to shift it left by s
bits.
First flip all the bits of n
(change all 0 bits to 1, and all 1 bits to 0). Then shift left by s
. That adds s
0 bits on the right. Then flip the bits again. The new trailing 0 bits are changed to 1 bits, and the original bits of n are restored.
>>> n = 5
>>> bin(n)
'0b101'
>>> ~(~n << 6)
383
>>> bin(_)
'0b101111111'