Bitwise Operators in Python:-
Bitwise operators perform bit by bit operations on
binary values of two operands.
1) Bitwise ‘and’ (‘&’) 2) Bitwise ‘or’ (‘|’)
3) Bitwise ‘xor’ (‘^’) 4) Negation (‘~’)
5) Bitwise ‘left shift’ (‘<<’) 6) Bitwise ‘right shift’ (‘>>’)
Bitwise ‘and’ (‘&’) :-
bit 1 bit 2 bitwise ‘&’
• Sets each bit to 1
1 1 1
if both bits are 1
0 1 0
1 0 0 Syntax :- op1 & op2
0 0 0
Operand types:-
1) int
a=5 00000101
2) binary
b=4 00000100
print(a & b)
Bitwise ‘or’ (‘|’) :-
bit 1 bit 2 bitwise ‘|’
• Sets each bit to 1
1 1 1 if atleast one of
0 1 1 both bits are 1
1 0 1
0 0 0
Syntax :- op1 | op2
Operand types:-
1) int
a=5 00000101
2) binary
b=4 00000100
print(a | b)
Bitwise ‘xor’ (‘^’) :-
bit 1 bit 2 bitwise ‘^’
• Sets each bit to 1
1 1 0 if both bits are
0 1 1 different.
1 0 1
Syntax :- op1 ^ op2
0 0 0
Operand types:-
1) int
a=5 00000101
2) binary
b=4 00000100
print(a ^ b)
Negation (‘~’) :-
bit 1 Negation
• 1 -> 0
1 0 • 0 -> 1
0 1
Syntax :- ~ op1
Operand types:-
1) int
a=5 00000101
2) binary
print(~a)
Left shift (‘<<’) :-
Left operand value is moved to left by the value of
bits present in right operand.
Syntax:- value << n
a=5 0000 0101
print(a << 2)
0
0 0 0 0 1 0 1
0 0 0 1 0 1 0 0
Right shift (‘>>’) :-
Left operand value is moved to right by the value of
bits present in right operand.
Syntax:- value >> n
a=5 0000 0101
print(a >> 2)
0
0 0 0 0 1 0 1
0 0 0 0 0 0 0 1