I have:
int8_t byteFlag;
and I want to get the first bit of it? I think I probably need to use &
and >>
but not sure how exactly. Any help?
int func(int8_t byteFlag, int whichBit)
{
if (whichBit > 0 && whichBit <= 8)
return (byteFlag & (1<<(whichBit-1)));
else
return 0;
}
Now func(byteFlag, 1)
will return 1'st bit from LSB. You can pass 8
as whichBit
to get 8th bit (MSB).
<<
is a left shift operant. It will shift the value 1
to the appropriate place and then we have to do &
operation to get value of that particual 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
.
You would use the & 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With