Skip to main content

Python: Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation.

Operators Description Syntax
Bitwise AND(&) Operator copies a bit to the result if it exists in both operands. a&b
Bitwise OR(|) It copies a bit if it exists in either operand. a|b
Bitwise XOR(^) It copies the bit if it is set in one operand but not both. a^b
Bitwise NOT(~) It inverts all the bits. ~a
Bitwise Right Shift(>>) It shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off. a>>
Bitwise Left Shift(<<) It shifts left by pushing zeros in from the right and let the leftmost bits fall off. a<<

Example: 

a = 20
b = 2

print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)

Output:

0
22
-21
22
5
80
Tags
Submitted by devanshi.srivastava on June 26, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.