C中是否有旋转操作

Are there rotate operations in C

来自组装书:

Another set of logical operations which apply to bit strings are the shift and rotate operations. These two categories can be further broken down into left shifts, left rotates, right shifts, and right rotates. These operations turn out to be extremely useful to assembly language programmers.

和:

Another pair of useful operations are rotate left and rotate right. These operations behave like the shift left and shift right operations with one major difference: the bit shifted out from one end is shifted back in at the other end.

它们在 C 中的循环操作等同于汇编中的 rotate 操作吗?

尽管 C 语言没有汇编的旋转移位对应物,但您当然可以通过将原始数字的最高/最低位与常规移位的结果进行 OR 运算来自己实现它们。

下面是无符号 32 位整数的示例:

uint32_t val = ... // This is the value being rotated
uint32_t rol = (val << 1) | (val >> 31);
uint32_t ror = (val >> 1) | (val << 31);

您可以将其概括为按任意位数循环,如下所示:

uint32_t val = ... // This is the value being rotated
uint32_t n = ... 
n &= 31;           // Force n into the range of 0..31, inclusive
uint32_t rol = (val << n) | (val >> (-n & 31));
uint32_t ror = (val >> n) | (val << (-n & 31));

使用 unsigned 类型很重要,因为否则右移将对值进行符号扩展,对于将符号位设置为 1.

的值会产生不正确的结果

感谢 Jester and Olaf 提出改进并将其推广到 n 位 n 移位的想法。

除了另一个答案:Microsoft 编译器具有生成 CPU 级旋转指令的内在函数:_rotl16_rotr16 等。它们是 CPU依赖,自然。

最新版本的 GCC 也有 _rotr_rotl