What Are Bitwise Operators?

Bitwise operators in Python perform operations on the binary representations of integer numbers. Instead of working on the values themselves, they manipulate individual bits (0s and 1s) of numbers. Bitwise operations are useful in low-level programming, performance-critical code, masking, encryption, and flag handling.

How Python Represents Numbers

Every integer has a binary representation inside the computer:

  • 5 in binary → 0101

  • 3 in binary → 0011

Bitwise operators operate on these bits directly.

List of Python Bitwise Operators

OperatorDescription
&Bitwise AND
|Bitwise OR
^Bitwise XOR
~Bitwise NOT
<<Left Shift
>>Right Shift

Examples of Bitwise Operators (Input & Output Together)

1. Bitwise AND (&)

Performs AND on each bit pair (1 only if both bits are 1):

Python
a = 5 # binary: 0101 b = 3 # binary: 0011 print(a & b) # Output: # 1

Explanation:

Python
0101 0011 ---- 0001 → 1

2. Bitwise OR (|)

Performs OR on each bit pair (1 if either bit is 1)

Python
a = 5 b = 3 print(a | b) # Output: # 7

Explanation:

Python
0101 0011 ---- 0111 → 7

3. Bitwise XOR (^)

Performs exclusive OR (1 only if bits differ)

Python
a = 5 b = 3 print(a ^ b) # Output: # 6

Explanation:

Python
0101 0011 ---- 0110 → 6

4. Bitwise NOT (~)

Flips all bits (one’s complement). In Python, this returns the negative two’s complement

Python
a = 5 print(~a) # Output: # -6

Explanation (conceptually):

Python
0101 → invert → 1010 → -6 in two’s complement

5. Left Shift (<<)

Shifts bits left and fills with 0s (equivalent to multiplying by powers of 2)

Python
a = 5 # 0101 print(a << 1) # Output: # 10

Explanation

Python
0101 << 1 → 1010 → 10

Each left shift doubles the value.

6. Right Shift (>>)

Shifts bits right (equivalent to integer division by powers of 2)

Python
 a = 10 # binary: 1010 print(a >> 1) # Output: # 5

Explanation:

Python
1010 >> 1 → 0101 → 5

Each right shift halves the value (floor division).

When to Use Bitwise Operators

Bitwise operators are useful when you need:

  • Masking bits (checking flags)

  • Toggling flags

  • Low-level data encoding and compression

  • Networking (IP address manipulation)

  • Cryptography and hashing