Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate right by n only using bitwise operators in C

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

like image 781
krb686 Avatar asked Nov 18 '25 22:11

krb686


1 Answers

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;
like image 174
jlahd Avatar answered Nov 20 '25 15:11

jlahd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!