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.
A:from T.
#include
main()
{
int shift(int,int);
int m = 33;
int n = 5;
printf("Rotating of %d to the right %d times results in %d\n",
m,n,shift(m,n));
}
int shift(int a,int b)
{
int c=a;
int i=0; //bit counter
int mask=1;
while(c!=0) //look for the most significant bit and set it=1
{
c=c>>1;
i++;
}
mask=mask<<(i1);
while(b>0) //rotate b times
{
if (a & 1)
{
a =a>>1;
a = a  mask;
}
else a =a>>1;
}
return a;
}
A:Kuniaki
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 signbit 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!
Kuniaki


