Skip to the workspace
Pebellslearn by building
Bitwise Operators  ›  Lesson

AND, OR, XOR and NOT

Bitwise Operators 12 minBitwise operators compare two numbers column by column: AND keeps a bit only where both are 1, OR where either is 1, XOR where exactly one is 1, and NOT flips every bit.

computer science / AND, OR, XOR and NOT

Explore each scene at your own pace.

01 · The rule

The rule

AND, OR, XOR and NOT

A settings screen has eight on/off switches. You could store eight separate true/false values, or you could store one byte where each bit is a switch. To read and change those switches you need operators that work on individual bits. Every mainstream language has them, usually written &, |, ^ and ~.

The rule

AND needs both, OR needs either, XOR needs exactly one, NOT flips.

Line the two numbers up in binary and work column by column, with no carrying between columns:

a b a AND b a OR b a XOR b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

NOT takes one number and flips every bit: in 8 bits, NOT 00001111 is 11110000. (In languages with signed integers, ~x equals −x − 1, because of how negative numbers are stored; Python's ~5 is −6.)

12 & 10   # AND  -> 8
12 | 10   # OR   -> 14
12 ^ 10   # XOR  -> 6

Do not confuse these with the logical operators and, or, &&, ||, which treat a whole value as true or false. Bitwise operators look inside the number.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.