C 旋转右位

C 旋转右位,c,bit-manipulation,bit,C,Bit Manipulation,Bit,我尝试在以下条件下向右旋转: /* * rotateRight - Rotate x to the right by n * Can assume that 0 <= n <= 31 * Legal ops: ~ & ^ | + << >> * Max ops: 25 * Rating: 3 */ 我已经关注这一点有一段时间了,不知道该怎么办(要么改变我的方法,要么改变我的算法),请建议比特天才 在没有看到您的

我尝试在以下条件下向右旋转:

 /*
  * rotateRight - Rotate x to the right by n
  *   Can assume that 0 <= n <= 31
  *   Legal ops: ~ & ^ | + << >>
  *   Max ops: 25
  *   Rating: 3
 */

我已经关注这一点有一段时间了,不知道该怎么办(要么改变我的方法,要么改变我的算法),请建议比特天才

在没有看到您的确切代码的情况下,我将其制作成一个程序,如下所示

#include <stdio.h>
#include <stdint.h>

uint32_t rotateRight( uint32_t x, uint32_t n )
{
    return (x >> n) | (x << (32+ (~n+1)) );
}


int main(){

    uint32_t value = 0x80000000;
    uint32_t newValue;

    newValue = rotateRight( value, 1 );

    printf( "orig: 0x%8.8x\n", value );
    printf( "new:  0x%8.8x\n", newValue );

    return 0;
}
注意:如果我用
int
替换
uint32\u t
,那么我将得到与您一样的0xc000000结果。处理位时,最好使用无符号类型。我总是使用未签名的类型来处理所有事情,除了我特别需要签名的少数情况

[编辑:这里有一个新的代码块,它接受int值]

#include <stdio.h>

int rotateRight( int x, int n )
{
    return (int)((unsigned)x >> n) | ((unsigned)x << (32+ (~n+1)) );
}

int main(){

    int value = -2147483648;
    int newValue;

    newValue = rotateRight( value, 1 );

    printf( "orig: %d\n", value );
    printf( "new:  %d\n", newValue );

    return 0;
}

在您的示例中,
rotateRight(0x87654321,4)=0x76543218
,在我看来,这是一个左旋转。同样,你的错误结果是与“应该”值相反的旋转。这实际上是一个打字错误。对不起……忽略这一点。是的,我知道,但这正是测试人员测试我的程序的方式,所以我对此无能为力。谢谢你的回答!在这种情况下,我建议在计算中将类型内部更改为无符号整数,并将其作为整数返回。
introtateright(intx,intn){return(int)((无符号)x>>n)|((无符号)我添加了一个不同版本的代码,它使用
int
值作为输入和输出helps@waterjuice你的alg工作得很好。返回时的外部int值不是严格要求的。我还用一些“更难”的值1和3测试了你的程序。它们也很好。
#include <stdio.h>
#include <stdint.h>

uint32_t rotateRight( uint32_t x, uint32_t n )
{
    return (x >> n) | (x << (32+ (~n+1)) );
}


int main(){

    uint32_t value = 0x80000000;
    uint32_t newValue;

    newValue = rotateRight( value, 1 );

    printf( "orig: 0x%8.8x\n", value );
    printf( "new:  0x%8.8x\n", newValue );

    return 0;
}
orig: 0x80000000
new:  0x40000000
#include <stdio.h>

int rotateRight( int x, int n )
{
    return (int)((unsigned)x >> n) | ((unsigned)x << (32+ (~n+1)) );
}

int main(){

    int value = -2147483648;
    int newValue;

    newValue = rotateRight( value, 1 );

    printf( "orig: %d\n", value );
    printf( "new:  %d\n", newValue );

    return 0;
}
orig: -2147483648
new:  1073741824