Bit masking in C - How to get the first bit of a byte?
I have:
int8_t byteFlag;
and I want to get its first bit? I think I probably need to use &
and >>
, but I'm not exactly sure how. Any help?
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
.
Just disguise the high beat
int8_t high_bit = byteFlag & (1 << 7); //either 1 or 0
Another trick as it is a signed int
if (byteFlag < 0) firstBitSet = true;
The latter works because of the two's complement representation of numbers. The high bit is set if the number is negative.
You must use the and operator.
If by "first bit" you mean LSB:
int firstBit = byteFlag & 1;
If by "first bit" you mean MSB:
int firstBit = byteFlag >> (sizeof(byteFlag) * 8 - 1);
int8_t bit_value = (byteFlag & (1U << bitPosition)) ? 1 : 0 ;
/* now it up to you to decide which bit is the "first".
bitPosition = 0 is the minor bit. */
The solution is given below. To get the first bit of a number, set bit = 1;
int bitvalue(int8_t num, int bit)
{
if (bit > 0 && bit <= 8)
return ( (num >> (bit-1)) & 1 );
else
return 0;
}