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 -> 6Do 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.
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.
What is 12 AND 10?
What is 12 OR 10?
What is 5 XOR 3?
What does x & 1 tell you?
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 logicalandandor.
