How Bitwise Operator Woks?

Bitwise Operators are used to do logical operations by each digits bit by bits. That means, first both operands are converted to binary number system and then operation is done.

We have bitwise AND &, bitwise OR |, bitwise NOT ~ and bitwise X-OR ^ operators for these operations.

Lets the the table below:

ABA & BA | B~ AA ^ B
000010
010111
100101
111100
  • AND Operator returns 1 if the corresponding bits of two operands is 1.
  • OR Operator returns 1 if at least one corresponding bit of two operands is 1.
  • NOT Operator returns 1 if corresponding bit is 0 and returns 0 if corresponding bit is 1. (It takes only one operand)
  • X-OR Operator returns 1 if the corresponding bits of two operands are opposite.


Examples

Bitwise AND

5 & 7
Converting each digits in binary:
    5 = 0101
    7 = 0111

Now,
      0101
    & 0111
    ------
      0101 = 5

That means,
    5 & 7 = 5
Bitwise OR
5 | 7
Converting each digits in binary:
    5 = 0101
    7 = 0111

Now,
      0101
    | 0111
    ------
      0111 = 7

That means,
    5 | 7 = 7
Bitwise NOT
~ 5
Converting each digits in binary:
    5 = 0101

Now,
    ~ 0101
    ------
      1010 = 10

That means,
    ~ 5 = 10
But if you try this while programming, you will get -6 as output. That is because result is calculated by 2's complement form. So, ~5 = 10 and 2's complement of 10 is -6.
You may have learned 2's complement earlier. But if not, here is easier formula:
bitwise complement of N = ~N (represented in 2's complement form)
2'complement of ~N= -(~(~N)+1) = -(N+1)

Bitwise X-OR
5 ^ 7
Converting each digits in binary:
    5 = 0101
    7 = 0111

Now,
      0101
    ^ 0111
    ------
      0010 = 2

That means,
    5 ^ 7 = 2