Bitwise operators are used to perform operations on binary digits or bits of a number. In Python, bitwise operators are used to perform bit-level operations on integers.
&
(and)|
(or)^
(xor)~
(not)<<
(left shift)||
(right shift)The &
operator compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1
, the corresponding result bit is set to 1
. Otherwise, the corresponding result bit is set to 0
.
x = 5 # binary: 101
y = 3 # binary: 011
result = x & y # binary: 001, decimal: 1
The |
operator compares each bit of the first operand to the corresponding bit of the second operand. If either bit is 1
, the corresponding result bit is set to 1
. Otherwise, the corresponding result bit is set to 0
.
x = 5 # binary: 101
y = 3 # binary: 011
result = x | y # binary: 111, decimal: 7
The ^
operator compares each bit of the first operand to the corresponding bit of the second operand. If the bits are different, the corresponding result bit is set to 1
. Otherwise, the corresponding result bit is set to 0
.
x = 5 # binary: 101
y = 3 # binary: 011
result = x ^ y # binary: 110, decimal: 6
The ~
operator inverts all the bits of the operand.
x = 5 # binary: 101
result = ~x # binary: 010, decimal: -6
The <<
operator shifts the bits of the operand left by the number of positions specified by the second operand.
x = 5 # binary: 101
result = x << 2 # binary: 10100, decimal: 20
The >>
operator shifts the bits of the operand right by the number of positions specified by the second operand.
x = 5 # binary: 101
result = x >> 2 # binary: 001, decimal: 1
Note: These operations are performed on the binary representation of the numbers, and the result is also represented in binary. To get the decimal value, we need to convert the binary result to decimal.