Rotate right by n only using bitwise operators in C
bit-manipulation, c, rotation
Solution
You could shift unsigned values:
y = (int)((unsigned)x >> n);
z = x << (32 - n);
g = y | z;
Or, you could mask appropriately:
y = (x >> n) & ~(-1 << (32 - n));
z = x << (32 - n);
g = y | z;
Problem
I'm trying to implement a rotateRight by n function in C by only using bitwise operators. So far, I have settled on using this. ``` y = x >> n z = x << (32 - n) g = y | z ``` So take for instance the value `11010011` If I were to try and `rotateRight(5): `y` becomes `11111110` `z` becomes `01100000` Then `g` becomes `111111110` However the correct answer should be `10011110` This almost works, but the problem is that the right-shift copies the sign bit when I need it to perform logical shift, and so some of my answers are the negative of what they should be. How can I fix this? Note I am unable to use casting or unsigned types