[c][k&r] プログラミング言語 C 2.8


右循環シフトを行う関数、 rightrot(x, n)を作れという問題。
初めは 1ビットずつ循環させるものを見ないといけないのかな〜と思ったけど、
考えてみると、先に下位 nビットを 上位 nビットに設定すればいいんですね。

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "util.h"

static unsigned int rightrot(unsigned int x, int n);
static void test_rightrot();

int
main (void)
{
     test_rightrot();

     printf("ans = %u\n", rightrot(0x1, 1));
}

static void
test_rightrot()
{
     assert(rightrot(0, 1)   == 0);
     assert(rightrot(1, 1)   == 0x80000000U);
     assert(rightrot(3, 2)   == 0xc0000000U);
     assert(rightrot(0xf, 4) == 0xf0000000U);
     assert(rightrot(0xffff, 16) == 0xffff0000U);
}

static
unsigned int rightrot(unsigned int x, int n)
{
     int i;
     unsigned int tmp;

     tmp = ~(~0 << n);
     tmp = x & tmp;
     tmp = tmp << ((sizeof(unsigned int) * 8) - n);

     return (x >> n) | tmp;
}