加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:08:52 所属栏目:百科 来源:网络整理
导读:我已经阅读了有关此问题的其他问题,但他们没有回答我的问题. 在下面的代码中我理解它检查该位是否已设置,但我的问题是为什么? bool test(uint8_t flag){ return flag (1 4);} 我不明白为什么它返回一个bool并且它有效,flag是uint8_t和1 4应该是这样的000100
我已经阅读了有关此问题的其他问题,但他们没有回答我的问题.

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

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 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读