Bit masking in C - How to get the first bit of a byte?
int func(int8_t byteFlag, int whichBit)
{
if (whichBit > 0 && whichBit <= 8)
return (byteFlag & (1<<(whichBit-1)));
else
return 0;
}
func(byteFlag, 1)
Will now return 1 bit from LSB. You can pass 8
like whichBit
to get the 8th bit (MSB).
<<
- left shift operand. It will move the value 1
to the appropriate location, and then we have to perform an operation &
to get the value of that private bit in byteFlag
.
for func(75, 4)
75 -> 0100 1011
1 -> 0000 0001
1 << (4-1) -> 0000 1000 //means 3 times shifting left
75 & (1 << (4 - 1))
will give us 1
.
source to share