循环右移

来源:百度知道 编辑:UC知道 时间:2024/06/01 10:07:39
对一个32位无符号整数做循环右移, 函数原型是unsigned int rotate_right(unsigned int x, int n);
所谓循环右移就是把低位移出去的部分补到高位去。
非常谢谢!

楼上是汇编版的,我来个C版的:
unsigned int rotate_right(unsigned int x, int n)
{
int save;
int i;
for(i=0;i<n;i++)
{
save=x&0x00000001;
x=x>>1;
save=save<<7;
x+=save;
}
return x;
}

typedef unsigned int uint;

uint rotate_right(uint x, int n)
{
uint result;
__asm
{
mov eax, x;
mov ecx, n;
Next:
ror eax, 1;
loop Next;
mov result, eax;
}
return result;
}

循环左移请将“ror”指令改为“rol”

unsigned int rotate_right(unsigned int x, int n)
{
return ((x&~(~1<<n-1))<<(32-n))|(x>>n);
}