Bitwise operators in python!

Bitwise operators in python!

Bitwise operators are those operators which operate on integers interpreted as bits ( binary digits 0 and 1 ). These operators operate bit by bit which means that the operands or the numbers to be operated on are converted to their binary representation to be worked upon.

Bitwise AND (&)

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

eg:

10 & 6
10: 0 0 0 0 1 0 1 0
6:  0 0 0 0 0 1 1 0
   ----------------
    0 0 0 0 0 0 1 0
This is the binary form of 2.
Ans. 10 & 6 = 2

Bitwise OR ( | )

1 | 0 => 1
0 | 1 => 1
1 | 1 => 1
0 | 0 => 0

eg:

10 | 6
10: 0 0 0 0 1 0 1 0
6:  0 0 0 0 0 1 1 0
   ----------------
    0 0 0 0 1 1 1 0
This is the binary form of 14.
Ans. 10 | 6 = 14

Bitwise NOT ( ~ )

~ 1 => 0
~ 0 => 1

eg:

~ 11
11: 0 0 0 0 1 0 1 1
   ----------------
    1 1 1 1 0 1 0 0    
This is the two's complement of 12.
Ans. ~ 11 = 12'

Bitwise Exclusive OR ( ^ )

1 ^ 0 => 1
0 ^ 1 => 1
1 ^ 1 => 0
0 ^ 0 => 0

eg:

10 ^ 6
10: 0 0 0 0 1 0 1 0
6:  0 0 0 0 0 1 1 0
   ----------------
    0 0 0 0 1 1 0 0 
This is the binary form of 12.
Ans. 10 ^ 6 = 12

Left Shift ( << )

Bits in the binary representation of x are shifted left by y places. Rightmost y bits of the result are filled with zeros.

eg:

5 << 2
5: 0 0 0 0 0 1 0 1
when shifted 2 positions to the left,
=> 0 0 0 1 0 1 0 0 
This is the binary form of 20.
Ans. 5 << 2 = 20

Right Shift ( >> )

Bits in the binary representation of x are shifted right by y places. Leftmost y bits of the result are filled with zeros.

eg:

5 >> 2
5: 0 0 0 0 0 1 0 1
when shifted 2 positions to the left,
=> 0 0 0 0 0 0 0 1 
This is the binary form of 1.
Ans. 5 >> 2 = 1

Precedence of bitwise operators

The precedence of operators in decreasing order is as follow.

Bitwise NOT
Left Shift 
Right Shift 
Bitwise AND
Bitwise Exclusive OR
Bitwise OR

Now, the precedence of arithmetic, logical, bitwise and relational operators in decreasing order is as follow.

Arithmetic operators
Bitwise operators
Relational operators
Logical operators

Hope you are following the notes. Comment below if you find them useful!!