C循环移位的错误答案

Poo*_*oya 3 c bit-manipulation shift

右移的实施是:

unsigned int rotr(unsigned int value, int shift) {
    return (value >> shift) | (value << (sizeof(value) * 8 - shift));
}
Run Code Online (Sandbox Code Playgroud)

但如果价值是0x17=00010111结果应该0x8b=10001011但结果是0x8000000b.

怎么处理这个问题?

#include <stdio.h>
unsigned int rotr(unsigned int value,int shift) {
    return (value >> shift) | (value << (sizeof(value) * 8 - shift));
}
int main()
{
  unsigned int a = 0x17;
  printf("%x",rotr(a,(unsigned)1));
}

=> 8000000b
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

这是以0x1732位整数旋转的正确结果:首先是

00000000 00000000 00000000 00010111
Run Code Online (Sandbox Code Playgroud)

你结束了

10000000 00000000 00000000 00001011
Run Code Online (Sandbox Code Playgroud)

如果要旋转8位数,请使用uint8_t而不是int作为函数参数:

uint8_t rotr(uint8_t value, int shift) {
    // No need to multiply by sizeof(value), because the type uint8_t forces it to be 1
    return (value >> shift) | (value << 8 - shift));
}
Run Code Online (Sandbox Code Playgroud)