为什么这个算法适用于反向位

时间:2016-06-06 14:15:20

标签: c++ c bit-manipulation

嘿家伙我对这个代码的变量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;

1 个答案:

答案 0 :(得分:0)

发布它只是为了说明它是如何工作的。希望它有所帮助:

#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(" - %02X\n", 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 while循环。
  • 每个循环将n的bit 1值存储到bit 1的{​​{1}}中,然后左移。
  • n的每个循环值右移以准备新位到n位置。