为什么此算法适用于反向位

Why does this algorithm work for reverse bit

本文关键字:适用于 算法 为什么      更新时间:2023-10-16

嘿伙计们,我对这段代码的变量 n 和 b 的用途感到困惑。我知道每行代码在做什么,我只是不明白它的重要性是如何反转的。如果有人能帮助理解每一行,那就太好了。我已经评论了我认为它的作用的一些代码行

        int r = 0;//initalizing r though it doesn't matter what value we use 
        while (b)//don't understand the meaning here
        {
            r <<= 1; //I know this means left shift one or multiply by 2
            r |= (n & 1);//I believe this line says AND the number with 1
            n >>= 1;//divide by 2
            b >>= 1;//divide by 2
        }
        return r;

发布它只是为了展示它是如何工作的。希望它有帮助:

#include <stdio.h>
#include <stdint.h>
void print8Bits( char *var_name, uint8_t value )
{
    uint8_t mask = 0x80;
    printf("%s = 0b", var_name);
    while (mask)
    {
        printf("%c", (value & mask) ? '1':'0');
        mask >>= 1;
    }
    printf(" - %02Xn", value);
}
int main(void)
{
    uint8_t b=5;
    uint8_t n=0xAA;
    uint8_t r = 0;//initalizing r though it doesn't matter what value we use+
    while (b)//don't understand the meaning here
    {
        r <<= 1; //I know this means left shift one or multiply by 2
        r |= (n & 1);//I believe this line says AND the number with 1
        n >>= 1;//divide by 2
        b >>= 1;//divide by 2
        print8Bits("r", r);
        print8Bits("n", n);
        print8Bits("b", b);
        printf("n");
    }
}

输出为:

r = 0b00000000 - 00
n = 0b01010101 - 55
b = 0b00000010 - 02
r = 0b00000001 - 01
n = 0b00101010 - 2A
b = 0b00000001 - 01
r = 0b00000010 - 02
n = 0b00010101 - 15
b = 0b00000000 - 00

如您所见:

  • 只要b有一个值!= 0 while 继续循环。
  • 每个循环的 n bit 1值都存储到 n bit 1中,然后左移。
  • n的每个循环值都右移,以准备一个新位到bit 1位置。