Python Mastery – From Basics to Brilliance / Operators in Python

Bitwise Operators

Bitwise operators work on numbers at the binary level (0s and 1s).

Though a bit advanced, they are super useful in fields like optimization, encryption, image processing, and hardware programming.


Operator

Symbol

What It Does

AND

&

Sets each bit to 1 if both bits are 1

OR

|

Sets each bit to 1 if at least one of the bits is 1

XOR

^

Sets each bit to 1 if only one of the bits is 1 (not both)

NOT

~

Inverts all bits (flips 0 to 1, and 1 to 0)

Left Shift

<<

Shifts bits to the left (adds zeros at the right)

Right Shift

>>

Shifts bits to the right (removes rightmost bits)


& Bitwise AND

x = 5
x & 3 # Output: 1

| Bitwise OR

x = 5
x | 3 # Output: 7

^ Bitwise XOR

x = 5
x ^ 3 # Output: 6

~ Bitwise NOT

x = 5
~x # Output: -6

<< Left Shift

x = 3
x << 1 # Output: 6

>> Right Shift

x = 8
x >> 1 # Output: 4