c - C中是否有旋转操作

标签 c assembly bitwise-operators

<分区>

摘自组装书:

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 的值产生不正确的结果。

谢谢 JesterOlaf用于改进和推广 n 位 n 移位的想法。

关于c - C中是否有旋转操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36986251/

相关文章:

c - 具有运算符优先级的宏函数是否显示异常结果?

c - 如何反转链表

c - 模拟 C 中各种结构的 array_pop

c - 如何化解这个二进制炸弹第 4 阶段

linux - source insight 中的汇编代码支持

c++ - 计算表示有符号整数所需的最小字节数

c - 如何找到动态数组的大小

c - 如何从这个输出中判断字节顺序?

c++ - 从程序集中调试用户的崩溃

opengl - 如何在 GLSL 1.3 和 OpenGL 2.1 中使用位操作