Page 49
Write a function rightrot(x,n)
that returns the value of the integer x
rotated to
the right by n
bit positions.
#include <limits.h>
#include <stdio.h>
unsigned rightrot(unsigned x, int n);
void print_bits(unsigned x);
unsigned get_leftmost_bit(unsigned x);
int main()
{
print_bits(rightrot(0b01000111, 3));
}
unsigned rightrot(unsigned x, int n)
{
return (x >> n) | ((x & ~(~0 << n)) << (sizeof(x) * CHAR_BIT - n));
}
void print_bits(unsigned x)
{
for (unsigned i = 1 << (sizeof(x) * CHAR_BIT - 1); i > 0; i >>= 1) {
if (i & x) {
putchar('1');
} else {
putchar('0');
}
}
}