C语言中没有提供循环移位的操作符, 但可以通过简洁的方式实现循环移位。
设一个操作数x有s位则循环左移n位的操作为:
(x << n) | (x >> (s - n)); 同理右移n位为:(x >> n) | (x << (s - n));
实际编程中可以用宏定义实现循环移位:
#define ROTATE_LEFT(x, s, n) ((x) << (n)) | ((x) >> ((s) - (n)))
#define ROTATE_RIGHT(x, s, n) ((x) >> (n)) | ((x) << ((s) - (n)))
例如:
C语言中实现循环移位#include <stdio.h>
#define ROTATE_LEFT(x, s, n) ((x) << (n)) | ((x) >> ((s) - (n)))
#define ROTATE_RIGHT(x, s, n) ((x) >> (n)) | ((x) << ((s) - (n)))
int main()
{
unsigned int a; scanf("%x", &a);
printf("%08x\n", a);
printf("%08x\n", ROTATE_LEFT(a, 8 * sizeof(int), 4));
printf("%08x\n", ROTATE_RIGHT(a, 8 * sizeof(int), 8));
return 0;
}
转载于:https://blog.51cto.com/activethink/224497