c – 它如何工作“检查位标志”

c – 它如何工作“检查位标志”,第1张

概述我已经阅读了有关此问题的其他问题,但他们没有回答我的问题. 在下面的代码中我理解它检查该位是否已设置,但我的问题是为什么? bool test(uint8_t& flag){ return flag & (1 << 4);} 我不明白为什么它返回一个bool并且它有效,flag是uint8_t和1<< 4应该是这样的00010000(我想).为什么该代码返回所需单个位的值而不是最右边的那 我已经阅读了有关此问题的其他问题,但他们没有回答我的问题.

在下面的代码中我理解它检查该位是否已设置,但我的问题是为什么?

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 – 它如何工作“检查位标志”所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1217953.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存