Home > Software design >  What is if (c >> a & 1) does mean?
What is if (c >> a & 1) does mean?

Time:11-12

I'm trying to understand what is this condition mean.

Does it mean after shifting the value it will be equal to 1?

I mean does it mean --> if (c >> a is 1)


Note: c >> a & 1 same as (c >> a) & 1.

CodePudding user response:

Bitwise AND operate on bits, so the possibilities are :

1101 & 0001 => 0001

0001 & 0001 => 0001

1010 & 0001 => 0000

0000 & 0001 => 0000

Now, on C, anything that's not a zero is treated as true, so the statement means "if after shifting the least significant bit is 1", or perhaps "if after shifting the value is odd" if you're dealing with odd-even operation.

CodePudding user response:

It executes the following statement or block if bit a of value c is true.

              a 1  a  a-1           1   0
       ... -- --- --- --- -- ... - --- --- 
             | z | y | x |        | q | p |
       ... -- --- --- --- -- ... - --- --- 


                             ... - --- --- 
>> a                              | z | y |
                             ... - --- --- 


                             ... - --- --- 
&& 1                              | 0 | y |
                             ... - --- --- 

CodePudding user response:

>> has higher operator precedence than &.

So c >> a & 1 means "shift the value c by a bits to the right, then check if the lowest bit of the shifted value is set. To single out certain bit values like this is known as bit masking and 1 in this case is the mask.

  • Related