Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit masking in C - How to get first bit of a byte?

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?

like image 934
Helen Avatar asked Jan 25 '13 18:01

Helen


Video Answer


2 Answers

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.

like image 135
rashok Avatar answered Oct 05 '22 22:10

rashok


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);
like image 36
itsme86 Avatar answered Oct 05 '22 22:10

itsme86