Home / Learn Chip Programming / Comparators and the ALU
Comparators and the ALU
The ALU is the calculator inside the CPU. See how one circuit does add, subtract, AND, OR, compare and shift and sets the flags.
Theory in plain words
What it is
An ALU takes two operands and an operation code, produces a result and sets flags: Zero, Negative, Carry and Overflow. A comparator is a subtraction that keeps only the flags.
Why we use it
All conditions in programs (if, while, for) are flag tests after an ALU operation. Understanding flags explains branch instructions and signed vs unsigned comparisons.
How it works
The control unit selects the operation with a few select lines. A multiplexer picks one of the results. Flags are one-bit registers updated after each operation.
Where it is used
- Every CPU and DSP
- Assembly conditional branches (BEQ, BNE, BGT)
- Writing a soft CPU in Verilog
ALU simulator
Set SUB with A = B and Z becomes 1: that is exactly how if (a == b) is implemented. C (borrow) tells you A is smaller than B for unsigned numbers; N and V together decide signed comparison.
| Flag | Name | Set when |
|---|---|---|
| Z | Zero | result is 0 |
| N | Negative | top bit of result is 1 |
| C | Carry / borrow | unsigned overflow in add, borrow in subtract |
| V | Overflow | signed overflow |
| H | Half carry (AVR) | carry out of bit 3, used for BCD |
| C condition | Typical branch | Test |
|---|---|---|
| a == b | BEQ | Z = 1 |
| a != b | BNE | Z = 0 |
| unsigned a < b | BLO / BCC | C = 1 |
| unsigned a >= b | BHS / BCS | C = 0 |
| signed a < b | BLT | N != V |
| signed a >= b | BGE | N = V |
Quick quiz
1. Which flag is set when a result is zero?
Z is the zero flag.
2. How is a comparison done in an ALU?
CMP is a SUB whose result is thrown away.
Common questions
Which flag is set when a result is zero?
Z. Z is the zero flag.
How is a comparison done in an ALU?
It subtracts and keeps only the flags. CMP is a SUB whose result is thrown away.