Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 439
user1655072 Avatar asked Oct 24 '12 17:10

user1655072


2 Answers

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.

like image 194
Xymostech Avatar answered Sep 29 '22 12:09

Xymostech


Actually, in C, C++ and other major programming languages the & operator do AND operations in each bit for integral types. The nth bit in a bitwise AND is equal to 1 if and only if the nth bit of both operands are equal to 1.

For example:

8 & 1 =
1000 - 8
0001 - 1
----
0000 - 0

7 & 1 =
0111 - 7
0001 - 1
----
0001 - 1

7 & 5 =
0111 - 7
0101 - 5
----
0101 - 5

For this reason doing a bitwise AND between an even number and 1 will always be equal 0 because only odd numbers have their least significant bit equal to 1.

like image 33
Murilo Vasconcelos Avatar answered Sep 29 '22 13:09

Murilo Vasconcelos