How I do circular shifting (rotation) of int in Python?

0

In Java right rotation is done using:

 (bits >>> k) | (bits << (Integer.SIZE - k))

But how to do similar thing in Python?

I tried to do (as described here):

n = 13
d = 2
INT_BITS = 4
print(bin(n))
print(bin((n >> d)|(n << (INT_BITS - d)) & 0xFFFFFFFF))

Output:

0b1101
0b110111

But I could not interpret this as a right rotation.

Also is it possible to perform the rotation by excluding leading zeroes, for example:

rightRotation of (...0001101) = 1110 not 1000...110

python
rotation
bit-shift
bitmask
asked on Stack Overflow Dec 3, 2019 by adnanmuttaleb • edited Dec 3, 2019 by adnanmuttaleb

1 Answer

0

It is my mistake, if you want to change INT_BITS to 4 you also need to change 0xFFFFFFFF to 0xF (one hex equals 4-bits):

n = 13
d = 2
INT_BITS = 4
print(bin(n))
print(bin((n >> d)|(n << (INT_BITS - d)) & 0xF))

will output:

0b1101
0b111
answered on Stack Overflow Dec 3, 2019 by adnanmuttaleb

User contributions licensed under CC BY-SA 3.0