对于这个问题,有两种思路,照旧,一种是我自己能想出来的方法,另一种是书上答案给出的方法。两种方法采用了两种不同的思路。
第一种方法,也就是我自己能想出来的方法,既然x循环右移n位,那就先得到最右边n位,然后将x右移n位,此时最左边n位为0,再将得到的最右边n位放到最左边。对于这种会出现循环的情况来说,需要考虑的一点就是机器使用的字长问题,如果n大于机器字长,那么循环机器字长的倍数次相当于没有移动,因此,可以令n = n % (wordlength()),(int wordlength(void)函数的作用是求得机器字长,在后边程序会给出)。
然后是具体过程:rbits = ~(~0<<n) & x 得到的是最右边n位是x的最右边n位,其余为0,然后,rbits << (wordlength() - n) 的作用是将最右边n位移动到最左边,然后将x右移n位,即 x>>n,最后 x | rbits,或操作可以得到最后的结果。
第二种方法,每次都向右移动一位,一共移动n次,具体实现思路和上一种方法类似,即先得到x最右边一位,然后移动到最左边:rbit = (x & 1) << (wordlength - 1);接下来将x向右移动一位:x >> 1;最后将x与rbit进行或操作:x | rbit。重复进行n次,得到x循环右移n位的结果。
参考代码:
#include<stdio.h>
unsigned rightrot(unsigned int x, int n)
{
int wordlength(void);
unsigned rbits;
if((n = n % wordlength()) > 0)
{
rbits = ~(~0 << x) & x;
rbits = rbits << (wordlength() - n);
x = (x >> n) | rbits;
}
return x;
}
unsigned rightrot_c(unsigned int x, int n)
{
int wordlength(void);
int rbit;
while(n-- > 0)
{
rbit = (x & 1) << (wordlength() - 1);
x = (x >> 1) | rbit;
}
return x;
}
int wordlength(void)
{
int i;
unsigned v = (unsigned) ~0;
for(i = 1; (v = v >> 1) > 0; i++)
;
// printf("%d\n", i);
return i;
}
int main()
{
unsigned int x = 129;
unsigned int y, z;
int n = 2;
y = rightrot(x, n);
z= rightrot_c(x, n);
printf("%d\n%d", y, z);
return 0;
}