在C语言中,我们可以使用位操作符进行左移和右移操作,但需要注意的是C语言没有直接的循环移位运算符。
以下是一个函数,它实现了二进制数字的循环左移和右移:
#include<stdio.h>
unsigned int leftRotate(unsigned int num, unsigned int rotation) {
unsigned int BITS = sizeof(num) * 8;
return (num << rotation)|(num >> (BITS - rotation));
}
unsigned int rightRotate(unsigned int num, unsigned int rotation) {
unsigned int BITS = sizeof(num) * 8;
return (num >> rotation)|(num << (BITS - rotation));
}
int main() {
unsigned int num = 15; // Binary: 00001111
unsigned int res = leftRotate(num, 2);
printf("%u", res); // Output: 60, which is 00111100 in binary
res = rightRotate(num, 2);
printf("n%u", res); // Output: 192, which is 11000000 in binary
return 0;
}
这里,unsigned int BITS = sizeof(num) * 8;
用来获取num的位数,num << rotation
实现左移,num >> rotation
实现右移。
|(num >> (BITS - rotation))
和 |(num << (BITS - rotation))
用来实现“循环”,也就是将被移出的位再移回来。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/173182.html