如何执行用C循环移位
问题描述:
我所描述的一个问题:如何执行没有嵌入汇编用C循环移位。为了更具体,如何旋转移位32位 INT
。
I have a question as described: how to perform rotate shift in C without embedded assembly. To be more concrete, how to rotate shift a 32-bit int
.
我现在正在解决这个问题,键入得到long long int
的帮助,但我认为它有点丑陋,想知道是否有一个更优雅的方法
I'm now solving this problem with the help of type long long int
, but I think it a little bit ugly and wanna know whether there is a more elegant method.
亲切的问候。
答
维基百科的code产生次优ASM(海合会包括分支或CMOV)。看到这个问题在C ++中循环移位(旋转)操作(或我的答案)的最佳实践。
Wikipedia's code produces sub-optimal asm (gcc includes a branch or cmov). See Circular shift (rotate) operations in C++ (or my answer on this question) for best-practices.
维基百科:
unsigned int _rotl(unsigned int value, int shift) {
if ((shift &= 31) == 0)
return value;
return (value << shift) | (value >> (32 - shift));
}
unsigned int _rotr(unsigned int value, int shift) {
if ((shift &= 31) == 0)
return value;
return (value >> shift) | (value << (32 - shift));
}