问题描述
我使用一个字节来存储像 10101010
这样的标志,我想知道如何验证特定位是在 1
还是 0.
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 <
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!