Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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.

The shortcut

Stack the numbers in binary and read down each column with the one-line rule. Two facts save time: x AND 1 is 1 exactly when x is odd, and x XOR x is always 0.

12 and 10, column by columnStep 1 of 4
  1. Write both in binary

    12 = 1100, 10 = 1010.

A handy check: OR always equals AND plus XOR. Here 14 = 8 + 6.

Drills

Answer fast — trust the rule.

quick drill

What is 12 AND 10?

quick drill

What is 12 OR 10?

quick drill

What is 5 XOR 3?

quick drill

What does x & 1 tell you?

quick drill

For any whole number x, what is x XOR x?

Remember

  • AND needs both, OR needs either, XOR needs exactly one, NOT flips.
  • Stack the binary and read each column; no carrying.
  • The trap: bitwise & and | are not the logical and and or.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainFour operators, one pair of numbers

Work out 12 AND 10, 12 OR 10 and 12 XOR 10, showing the binary columns. Then explain how x AND 1 tells you whether x is odd, and why x XOR x is always 0.