Search code examples
c++bitwise-operators

How does condition statement work with bit-wise operators?


I tried to understand how if condition work with bitwise operators. A way to check if a number is even or odd can be done by:

#include <iostream>
#include <string>
using namespace std;

string test()
{
    int i = 8;  //a number
    if(i & 1)
      return "odd";

    else
      return "even";       
}

int main ()
{
  cout << test();
  return 0;
}

The Part I don't understand is how the if condition work. In this case if i = 8 then the in If statement it is doing 1000 & 1 which should gives back 1000 which equal 8.

If i = 7, then in if statement it should be doing 111 & 1 which gives back 111 which equal 7

Why is it the case that if(8) will return "even" and if(7) return "odd"? I guess I want to understand what the if statement is checking to be True and what to be False when dealing with bit-wise operators.

Just A thought when I wrote this question down is it because it's actually doing

for 8: 1000 & 0001 which gives 0
for 7: 0111 & 0001 which gives 1?

Solution

  • Yes, you are right in the last part. Binary & and | are performed bit by bit. Since

    1 & 1 == 1
    1 & 0 == 0
    0 & 1 == 0
    0 & 0 == 0
    

    we can see that:

    8 & 1 == 1000 & 0001 == 0000
    

    and

    7 & 1 == 0111 & 0001 == 0001
    

    Your test function does correctly compute whether a number is even or odd though, because a & 1 tests whether there is a 1 in the 1s place, which there only is for odd numbers.