我正在尝试用 C++ 编写一个 ROL 函数,并且看到了一些与之相关的问题。以我的知识,我并不真正理解它是如何工作的。
我正在使用下面的代码
#include<stdio.h>
#define INT_BITS 32
using namespace std;
int leftRotate(int n, unsigned d){ //rotate n by d bits
return (n << d)|(n >> (INT_BITS - d));
}
int main() {
int n = 0xa3519eba;
int d = 0x0f;
printf("Left rotation of %d by %d is ", n, d);
printf("%d", leftRotate(n, d));
}
我期待 0xcf5d51a8 的结果,但我得到的是签名 0x2e58。
任何关于我哪里出错的方向都将不胜感激。
最佳答案
由于符号位,当您尝试对有符号值进行位运算时会发生有趣的事情。
#include<stdio.h>
#define INT_BITS 32
int leftRotate(unsigned n, unsigned d){ //rotate n by d bits
return (n << d)|(n >> (INT_BITS - d));
}
int main() {
unsigned n = 0xa3519eba;
unsigned d;
for( d = 0; d < 32; d += 4 )
printf("Left rotation of 0x%.8X by %d is 0x%.8X\n", n, d, leftRotate(n, d));
}
输出:
Left rotation of 0xA3519EBA by 0 is 0xA3519EBA
Left rotation of 0xA3519EBA by 4 is 0x3519EBAA
Left rotation of 0xA3519EBA by 8 is 0x519EBAA3
Left rotation of 0xA3519EBA by 12 is 0x19EBAA35
Left rotation of 0xA3519EBA by 16 is 0x9EBAA351
Left rotation of 0xA3519EBA by 20 is 0xEBAA3519
Left rotation of 0xA3519EBA by 24 is 0xBAA3519E
Left rotation of 0xA3519EBA by 28 is 0xAA3519EB
关于c++ - 在 C++ 中向左旋转 x 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38775878/