为什么此算法适用于反向位
Why does this algorithm work for reverse bit
嘿伙计们,我对这段代码的变量 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
位置。
相关文章:
- OpenGL - 在 NDC 中计算位置适用于着色器,但不适用于'regular'程序
- 使用模板参数重载C++方法:如何使其适用于模板的子类?
- 如何修复我的最大公约数代码?它适用于除零和零以外的所有数字
- 选择排序C++(已修改)并非适用于所有情况
- 无法让"std::enable_if"适用于无作用域枚举
- 请找出我的代码中的错误,它在提交得到错误答案的同时仍然适用于我的所有测试用例
- 确定夏令时是否适用于特定日期
- 是否有一种 STL 算法可以最后找到,但它也适用于指针?
- QT 样式表主题,适用于使用属性选择器的整个应用程序
- C++带有适用于左值和右值的引用参数的函数
- 代码适用于调试,但不适用于发布
- C++17 和更新的 std::分配器是否适用于动态数量的自定义堆?
- 适用于大型数组的无复制线程安全环形缓冲区
- NRVO 是否也适用于协程?
- 指针算法是否适用于迭代器?
- STL 算法 + c'tor 不再适用于指向 C 数组的原始指针,因为指向一个过去的末端
- 为什么此算法适用于反向位
- 适用于大文件和 512 KB 块的最快和轻量级哈希算法 [C,Linux,MAC,Windows]
- 什么是适用于多个入口和多个出口的类似BFS的最佳路径算法
- c++:应用于向量的STL算法也适用于其他容器对象