0 c assembly bitwise-operators
从装配书:
应用于位串的另一组逻辑运算是移位和旋转操作.这两个类别可以进一步细分为左移,左旋,右移和右旋.这些操作对汇编语言程序员非常有用.
和:
另一对有用的操作是向左旋转并向右旋转.这些操作的行为类似于左移和右移操作,但有一个主要区别:从一端向外移出的位在另一端向后移位.
他们在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);
Run Code Online (Sandbox Code Playgroud)
您可以将其概括为按任意位数旋转,如下所示:
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));
Run Code Online (Sandbox Code Playgroud)
使用unsigned
类型很重要,因为否则右移会对值进行符号扩展,从而对其符号位设置为的值产生不正确的结果1
.