➕ Operators & Expressions
Module 3 · Topic 4

Bitwise Operators

Manipulate individual bits of integers — essential for systems programming, cryptography, and performance optimization.

Theory

Bitwise Operators:

| Operator | Name | Example | Result |
|----------|------|---------|--------|
| & | AND | 5 & 3 | 1 |
| | | OR | 5 | 3 | 7 |
| ^ | XOR | 5 ^ 3 | 6 |
| ~ | NOT (complement) | ~5 | -6 |
| << | Left shift | 5 << 1 | 10 |
| >> | Right shift | 5 >> 1 | 2 |

How it works (5 = 0101, 3 = 0011):

  • AND (&): 0101 & 0011 = 0001 (1) — both bits must be 1
  • OR (|): 0101 | 0011 = 0111 (7) — either bit is 1
  • XOR (^): 0101 ^ 0011 = 0110 (6) — bits must differ
  • NOT (~): ~0101 = -(0101 + 1) = -6 (two's complement)
  • Left shift (<<): multiply by 2^n — 5 << 1 = 10
  • Right shift (>>): divide by 2^n — 5 >> 1 = 2

Practical Uses:

  • Flags/permissions: READ = 4; WRITE = 2; EXEC = 1; perms = READ | WRITE
  • Fast multiply/divide by powers of 2: x << 3 = x * 8
  • Check if even: n & 1 == 0
  • Swap without temp: a ^= b; b ^= a; a ^= b
Syntax
a & b    # Bitwise AND
a | b    # Bitwise OR
a ^ b    # Bitwise XOR
~a       # Bitwise NOT
a << n   # Left shift by n
a >> n   # Right shift by n