Q:For bit manipulation C has some operators. Write a function rotate(m,n) that returns
the value of integer m rotated to the right by n positions.
int m = 33;
int n = 5;
printf("Rotating of %d to the right %d times results in %d\n",
int shift(int a,int b)
int i=0; //bit counter
while(c!=0) //look for the most significant bit and set it=1
while(b-->0) //rotate b times
if (a & 1)
a = a | mask;
else a =a>>1;
I have read your technial interview question and they are great! However, this question puzzles me...
First, you are using signed data type. What if you are rotating NEGATIVE values? Then, if you are shifting right, the sign-bit will carry over resulting to an incorrect answer. Second, what if you are rotating by 64 bits (for the second argument for 'rotate')? Theoretically, rotating by 64 should do anything. So before doing all of the masking and shifting, you should mod the second parameter by 32. So you will deal with the leftovers (if there are any).
Thank you! And please keep up the good work!