在下面的代码中我理解它检查该位是否已设置,但我的问题是为什么?
bool test(uint8_t& flag){ return flag & (1 << 4);}
我不明白为什么它返回一个bool并且它有效,flag是uint8_t和1<< 4应该是这样的00010000(我想).为什么该代码返回所需单个位的值而不是最右边的那个或类似的东西?
解决方法 C++ draft standard部分4.12布尔转换说(强调我的):A prvalue of arithmetic,unscoped enumeration,pointer,or pointer to member type can be converted to a prvalue of type bool. A zero value,null pointer value,or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5),a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.
因此任何非零值都将转换为true.
你对1<<< 1< 1< 1< 1的结果表示怀疑. 4我们有一个快速的方法来检查使用std::bitset:
#include <bitset>#include <iostream>int main() { std::bitset<8> b1(1<<4); std::cout << b1 << std::endl ; return 0;}
并且我们可以看到结果确实是00010000,因为如果两个 *** 作数中的位都是1,则bitwise and仅将位设置为1,然后是flag&的结果.如果flag的bit 5也是1,则(1 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
总结以上是内存溢出为你收集整理的c – 它如何工作“检查位标志”全部内容,希望文章能够帮你解决c – 它如何工作“检查位标志”所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)