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 bit
:
bool is_bit_set(unsigned value, unsigned bitindex)
{
return (value & (1 << bitindex)) != 0;
}
Explanation:
The left shift operator <<
creates a bitmask. To illustrate:
(1 << 0)
equals 00000001
(1 << 1)
equals 00000010
(1 << 3)
equals 00001000
So a shift of 0
tests the rightmost bit. A shift of 31
would be the leftmost bit of a 32-bit value.
The bitwise-and operator (&
) gives a result where all the bits that are 1
on both sides are set. Examples:
1111 & 0001
equals 0001
1111 & 0010
equals 0010
0000 & 0001
equals 0000
.So, the expression:
(value & (1 << bitindex))
will return the bitmask if the associated bit (bitindex
) contains a 1
in that position, or else it will return 0
(meaning it does not contain a 1
at the assoicated bitindex
).
To simplify, the expression tests if the result is greater than zero
.
Result > 0
returns true
, meaning the byte has a 1
in the tested
bitindex
position.false
meaning the result was zero, which means there's a 0
in tested bitindex
position.Note the != 0
is not required in the statement since it's a bool, but I like to make it explicit.