I'm studing C on K&R and I solved exercise 2.08 ("Write a function rightrot(x,n) that returns the value of the integer x rotated to the right by n positions") with the code below. I've tested my code with some bit patterns and it seems to work, but I'm not sure that this solution covers all possible cases. What do you think about this code?
unsigned rightrot(unsigned x, int n)
{
int size;
unsigned y;
size = 0;
y = x;
while (y != 0) {
y = y << BYTESIZE;
size++;
}
size = size * BYTESIZE;
return (x << (size-n)) | (x >> n);
}
Here is the main
#include <stdio.h>
#define BYTESIZE 8
unsigned rightrot(unsigned x, int n);
int main(void)
{
unsigned x;
int n;
x = 0x23acb;
n = 2;
printf("%x\n", rightrot(x, n));
return 0;
}