Lesson 33 +10 XP

Bitwise Operators

Bitwise operators work on the binary bits of integers. They're used in low-level programming.

OperatorNameExample
&ANDx & y
``OR`xy`
^XORx ^ y
~NOT~x
<<Left shiftx << 2
>>Right shiftx >> 2

A quick example


python
print(6 & 3)

### 2
print(6 | 3)

### 7
print(6 ^ 3)

### 5
print(~6)

### -7
print(5 << 1)

### 10  (shift left = multiply by 2)
print(5 >> 1)

### 2   (shift right = divide by 2)

What's happening

6 in binary is 110, and 3 is 011:

  • AND keeps bits where both are 1: 010 = 2
  • OR keeps bits where either is 1: 111 = 7
  • XOR keeps bits where exactly one is 1: 101 = 5

Shifts

<< moves bits left (doubling), >> moves them right (halving):


python
print(1 << 3)

### 8
print(8 >> 2)

### 2

When to use them

Most everyday Python code never touches bits. They shine for:

  • flags and permission systems
  • graphics and compression
  • performance-critical math

TL;DR

  • & AND, | OR, ^ XOR, ~ NOT.
  • << and >> shift bits left and right.
  • A left shift by one doubles; a right shift by one halves.
  • Mostly for low-level and performance work.