-1

I don't understand the use of the operators & and == in the following piece of code:

Static boolean foo(){

    long stat;
    /* ...code*/

    if (!(stat & 1)){
     /* code... */
    }

     return (stat == SOME_MACRO);
 }
  • What does & do inside the if comparison?
  • What does == do inside the return ?

Thanks in advance.

Cédric Julien
  • 74,806
  • 15
  • 120
  • 127

3 Answers3

3

& is a bitwise AND, which is testing whether the least significant bit of stat is set.

The == makes the function return 1 (meaning "true") if stat is equal the value of to SOME_MACRO. Otherwise it returns 0 (meaning "false").

RichieHindle
  • 258,929
  • 46
  • 350
  • 392
1

if (state & 1) is same is if state is odd.

return (stat == SOME_MACRO); is same as

if (state == SOME_MACRO)
    return true;
else
    return false;

Explanation: The binary representation of any odd number would have a 1 at its last digit. For example,

3 = 11
5 = 101
7 = 111

If you already know what & does, you will notice that when you perform n & 1, all bits except the last one is set to zero, and the last bit remain unchanged. So n & 1 returns the last bit of n, which is 1 if n is odd, and 0 if n is even.

And (state == SOME_MACRO) will evaluate to true if the expression is True, and evaluate to false if the expression is False. So it will return either true or false depending if state is equal to SOME_MACRO or not.

Rafi Kamal
  • 4,412
  • 8
  • 35
  • 48
1

The & (bitwise AND) operator compares each bit of its first operand to the corresponding bit of the second operand. If both bits are 1's, the corresponding bit of the result is set to 1. Otherwise, it sets the corresponding result bit to 0.

the function will return true if stat equal to SOME_MACRO, false otherwise

Flavia Obreja
  • 1,227
  • 7
  • 13