Assuming that an unsigned int
is 32 bits long, the
simplest way to approach this problem would be to shift x
n bits to the right, and use the OR operator on that and
x shifted 32 - n
bits to the left (this moves
the rightmost n bits to the leftmost positions.)
/* rightrot: returns x rotated to the right by n bit positions */
unsigned rightrot(unsigned x, int n)
{
return (x >> n) | (x << (32 - n));
}
However, there is one major issue with this solution: it
assumes that an unsigned int
is 32-bit.
Remember, this is implementation-defined! So we have to find a way to
rotate the bits that works regardless of the length of the bit string.
The simplest way to do this would be to use a for
-loop
that runs n times and rotates the integer bit-by-bit. If the
last bit is a one (we can check for this by masking all but the last
bit: x & 1U == 1U
), in addition to shifting to the right
by one, we also replace the leftmost bit with a one. To achieve this,
we use the OR operator on the shifted string and a bit string with one
in the leftmost position and zeros in the remaining positions. We can
create the second bit string by starting with ~0U
,
shifting it one to the right, and inverting it.
/* rightrot: return x rotated to the right by n bit positions */
unsigned rightrot(unsigned x, int n)
{
for (; n > 0; --n) {
if ((x & 1U) == 1U)
x = (x >> 1) | ~(~0U >> 1);
else
x = x >> 1;
}
return x;
}