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.

In shortThe 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

Inside an ALUOperand A and B (registers)Adder/subtractor, logic unit, shifter work in parallelMultiplexer selects the result by opcodeFlag logic: Z, N, C, V
Inside an ALU

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

8 bit ALU with flagsTry it Yourself

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.

FlagNameSet when
ZZeroresult is 0
NNegativetop bit of result is 1
CCarry / borrowunsigned overflow in add, borrow in subtract
VOverflowsigned overflow
HHalf carry (AVR)carry out of bit 3, used for BCD
C conditionTypical branchTest
a == bBEQZ = 1
a != bBNEZ = 0
unsigned a < bBLO / BCCC = 1
unsigned a >= bBHS / BCSC = 0
signed a < bBLTN != V
signed a >= bBGEN = V

Quick quiz

1. Which flag is set when a result is zero?

2. How is a comparison done in an ALU?

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.