C - 我在编写"rotate right"函数时遇到问题



我在编写代码以正确旋转十六进制数字时遇到了一点麻烦。下面是我写的一个函数,如果你调用它,像这样传递它:rotr(0x12345678, 4(,它应该返回0x81234567。相反,它只返回 7 位数字(而不是 8 位,如原始值 = 0x12345678(。

有人可以帮我了解位级别发生了什么吗?我无法理解为什么我当前的代码返回0x123456f而不是0x81234567。提前感谢!

编辑:是因为我过早转移0x12345678吗?我主要是想弄清楚为什么只有七位数字返回,而不是八位。

unsigned int rotr(unsigned int x, int n) {
    int i; //iterate for loop
    unsigned int y; //masked last bit
    unsigned int z; //final result
    for (i=1; i<=n; i++) {
        y = x & 0x1; //isolates last bit
        x = x >> 1; //shift right 1
        z = x | (y << (sizeof(x)-1)); //shifts mask back to first slot; OR
                                      //it with x
    }
    return z;
}

sizeof(x)将以字节为单位给出变量的大小,而移位运算符则使用位数。您需要将这些操作数转换为使用相同的单位。

而不是sizeof(x)你应该写8*sizeof(x),它看起来很通用,因为你的输入可能是short int,long int或其他任何东西。

对于右旋转而不是旋转循环,您可以尝试以下逻辑。

#include<stdio.h>
unsigned int rotr(unsigned int x, int n) {
        unsigned int z;
        z = (x >> n) | (x << (8*sizeof(int) - n)) ; 
        return z;
}
int main()
{
        unsigned  int num= 0x12345678, n = 4, ret;
        printf("before : %xn",num);
        ret= rotr(num,n);
        printf("before : %xn",ret);
}

最新更新