如何检查我的字节标志? [英] How to check my byte flag?
问题描述
我用一个字节来存储一些标志,比如 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 <<;&小于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。所以,前pression(价值及(1 LT;&LT;位索引))将返回位掩码如果相关的位是值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.)
这篇关于如何检查我的字节标志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!