如何检查我的字节标志,以验证特定位是1还是0? [英] How can I check my byte flag, verifying that a specific bit is at 1 or 0?

查看:77
本文介绍了如何检查我的字节标志,以验证特定位是1还是0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个字节来存储诸如10101010之类的标志,并且我想知道如何验证特定位在10上.

I use a byte to store some flag like 10101010, and I would like to know how to verify that a specific bit is at 1 or 0.

推荐答案

以下是可用于测试任何所需位的函数:

Here's a function that can be used to test any desired bit:

bool is_bit_set(unsigned value, unsigned bitindex)
{
    return (value & (1 << bitindex)) != 0;
}

一些解释:

左移运算符(<<)用于创建位掩码. (1< 0)等于00000001,(1<< 1)等于00000010,(1<< 3)等于00001000,依此类推.因此,移位0个测试最右边的位. 31的移位将是32位值的最左位.

The left shift operator (<<) is used to create a bit mask. (1 << 0) will be equal to 00000001, (1 << 1) will be equal to 00000010, (1 << 3) will be equal to 00001000, etc. So a shift of 0 tests the rightmost bit. A shift of 31 would be the leftmost bit of a 32-bit value.

按位与运算符(&)给出的结果是,将两侧的所有位都设置为1.示例:1111& 0001 = 0001; 1111& 0010 == 0010; 0000& 0001 =0000.因此,表达式(value&(1<< bitindex))如果关联的位的值为1,则将返回位掩码,如果关联的位为0,则将返回0.

The bitwise-and operator (&) gives a result where all the bits that are 1 on both sides are set. Examples: 1111 & 0001 = 0001; 1111 & 0010 == 0010; 0000 & 0001 = 0000. So, the expression (value & (1 << bitindex)) will return the bitmask if the associated bit is 1 in value, or will return 0 if the associated bit is 0.

最后,我们只检查结果是否为非零. (实际上可以将其排除在外,但我想明确指出.)

Finally, we just check whether the result is non-zero. (This could actually be left out, but I like to make it explicit.)

这篇关于如何检查我的字节标志,以验证特定位是1还是0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆