Originally Posted by
olbas
Why does it seem like I have done it wrongly.. I did what the exercise requested, yet mine seems somewhat simplier. Any comments on why this is?
The test values you use don't demonstrate any difference between a bitwise rotation and a bitwise shift. If you had chosen different values, then the difference would be more noticeable.
Code:
#include <stdio.h>
unsigned rightrot1(unsigned x, unsigned n)
{
while ( n > 0 )
{
if ( (x & 1) == 1 )
x = (x >> 1) | ~(~0U >> 1);
else
x = (x >> 1);
n--;
}
return x;
}
unsigned rightrot2(unsigned a, unsigned b)
{
return(a >> b);
}
int main(void)
{
unsigned result;
unsigned x = 12;
unsigned n = 2;
result = rightrot1(x, n);
printf("rightrot1(%u, %u) = %u = %x\n", x, n, result, result);
result = rightrot2(x, n);
printf("rightrot2(%u, %u) = %u = %x\n", x, n, result, result);
x = 0x1234U;
n = 8;
result = rightrot1(x, n);
printf("rightrot1(%u, %u) = %u = %x\n", x, n, result, result);
result = rightrot2(x, n);
printf("rightrot2(%u, %u) = %u = %x\n", x, n, result, result);
return 0;
}
/* my output
rightrot1(12, 2) = 3 = 3
rightrot2(12, 2) = 3 = 3
rightrot1(4660, 8) = 872415250 = 34000012
rightrot2(4660, 8) = 18 = 12
*/