c++ - 在 C++ 中向左旋转 x 位

标签 c++

我正在尝试用 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/

相关文章:

c++ - 无法将参数 8 从 'int' 转换为 'cv::HOGDescriptor::HistogramNormType'

c++ - C++ 位域为什么以及如何不可移植?

c++ - 程序结构

c# - 使用托管 C++ 包装器将字符串从 C# 传递到非托管 C#

c++ - 内核和驱动程序有什么区别?

C++:读取带分隔符的文件并存储在结构中

c++ - 使用C/C++转义unicode字符

c++ - vc++ 中预期的常量表达式

c++ - Thread Building Blocks 流程图 — 类似 limiter_node 的东西,不会丢弃消息

c++ - 为什么程序在不暂停的情况下关闭?(C++)