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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With