Logic and bit operations

Module 3 · Logic and bit operations · Lesson 3 of 6

Bitwise operators

There are four bitwise operators, and each is the bit-level twin of a logical idea: & (AND), | (OR), ^ (XOR, “exclusive or”) and ~ (NOT). They line numbers up in binary and combine them column by column.

12 and 10, bit by bit
12 =
1100
10 =
1010
& =
1000
= 8
| =
1110
= 14
^ =
0110
= 6

& needs both 1 · | needs either 1 · ^ needs exactly one 1

Each column follows a simple rule. & gives a 1 only when both bits are 1. | gives a 1 when either is. And ^ gives a 1 only when the bits differ — exactly one of them is 1.

Run it yourselfruns in your browser · Python
main.py

The odd one out is ~ (NOT), which takes a single number and flips every bit. Because of how Python stores negative numbers, the tidy result is that ~x equals -(x + 1) — so ~12 is -13. Don't worry about memorising that; just know ~ inverts the bits.