嘿家伙我对这个代码的变量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;
答案 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循环。bit 1
值存储到bit 1
的{{1}}中,然后左移。n
的每个循环值右移以准备新位到n
位置。