Bitwise operators work directly on the binary representation of numbers. They're essential for bit manipulation problems and can provide elegant, efficient solutions to certain problems.
The Six Bitwise Operators
AND (&)
Returns 1 only if both bits are 1. Useful for checking if a bit is set or clearing bits.
OR (|)
Returns 1 if at least one bit is 1. Useful for setting bits.
XOR (^)
Returns 1 if bits are different. XOR has special properties: a ^ a = 0, a ^ 0 = a, and it's commutative and associative.
NOT (~)
Flips all bits. In Python, ~n = -(n+1) due to two's complement representation.
Left Shift (<<)
Shifts bits left, filling with zeros. Equivalent to multiplying by 2^n.
Right Shift (>>)
Shifts bits right. Equivalent to integer division by 2^n.