---
title: The arithmetic logic unit
heading: One block that adds, subtracts, ANDs and ORs, and the four flags that let a program compare
eyebrow: C7 · Lesson 18 · The arithmetic logic unit
xp: 40
---

::: hook
Lesson 17 built adders. A processor needs more than addition from the same hardware: subtraction, comparison, the logical operations, all selected by a few control bits from the instruction. That block is the **arithmetic logic unit**, and alongside its result it reports four facts about it: was the result zero, was it negative, did an unsigned operation carry out, did a signed one overflow? Those four flags are how every comparison in a program is made, and getting them right is a small, exact exercise in two's complement.
:::

::: play
- A 2-bit ALU built from two slices. `Op1 Op0` selects the operation: 00 AND, 01 OR, 10 ADD, 11 SUBTRACT. Flip the inputs and watch the result and flags.
- Subtraction is addition with $B$ inverted and a carry of 1 into the lowest slice: $A - B = A + \bar B + 1$.
- Try $A$ = 01, $B$ = 01 with SUBTRACT: the result is 00, $Z$ lights, and $C$ = 1 because no borrow was needed.
:::

```sim logic
input A1, A0, B1, B0, Op1, Op0
output R1, R0, Z, N, C, V
set Op1 = 1
set Op0 = 1
set A0 = 1
set B0 = 1
assign sub = Op1 & Op0
assign x0 = B0 ^ sub
assign x1 = B1 ^ sub
assign s0 = A0 ^ x0 ^ sub
assign c1 = A0 & x0 | (A0 ^ x0) & sub
assign s1 = A1 ^ x1 ^ c1
assign c2 = A1 & x1 | (A1 ^ x1) & c1
assign R0 = Op1 ? s0 : (Op0 ? A0 | B0 : A0 & B0)
assign R1 = Op1 ? s1 : (Op0 ? A1 | B1 : A1 & B1)
assign Z = ~(R1 | R0)
assign N = R1
assign C = Op1 & c2
assign V = Op1 & (c1 ^ c2)
```

::: predict
## A 4-bit ALU computes 5 − 7 by adding 0101, 1010 and a carry-in of 1. What are the result and the carry out?

- [x] 1110 with carry out 0
- [ ] 1110 with carry out 1
- [ ] 0010 with carry out 0
- [ ] 0010 with carry out 1

::: reveal
$0101 + 1010 + 1 = 1110$, which is −2 in two's complement, with no carry out of the top bit. In this convention (used by RISC-V comparisons, ARM and the 6502), a carry of 0 after a subtraction means a borrow happened: unsigned 5 is less than unsigned 7.
:::
:::

::: nameit
## Bit slices and function select

An $n$-bit ALU is $n$ copies of a one-bit slice: a full adder, the logic gates, and a multiplexer that picks the slice's output according to the operation code. The adder's carries ripple (or look ahead) from slice to slice, and subtraction reuses them: XOR gates invert $B$ when subtracting, and the lowest carry-in is set to 1, because $-B = \bar B + 1$ in two's complement.

## The four flags

After an operation producing result $R$ with carries $c_n$ out of the top bit and $c_{n-1}$ into it:

| Flag | Meaning | Logic |
|---|---|---|
| Z, zero | $R = 0$ | NOR of all result bits |
| N, negative | $R$'s sign bit | $R_{n-1}$ |
| C, carry | unsigned carry out; after a subtraction, 1 means no borrow | $c_n$ |
| V, overflow | the signed result didn't fit | $c_n \oplus c_{n-1}$ |

Overflow can be detected two ways that always agree: the carries into and out of the sign bit differ, or two operands of the same sign produced a result of the other sign (lesson 17).

## Comparisons from flags

Compute $A - B$ and discard the result:

- $A = B$: Z = 1.
- Unsigned $A < B$: C = 0 (a borrow).
- Signed $A < B$: $N \oplus V = 1$. The sign bit alone is wrong when the subtraction overflowed, and the XOR corrects it.

That's what a "compare" instruction does, and what conditional branches test. RISC-V skips the flags register and computes the comparison directly in the branch instruction, but the logic inside is the same.

## Speed

The ALU's critical path is the carry chain: in a ripple design, about two gate delays per bit, plus the multiplexer, plus the zero detector, which is a tree of $\lceil\log_2 n\rceil$ levels of 2-input gates. Lookahead adders shorten the chain to a few levels, which is why fast ALUs use them.
:::

::: example
## A 4-bit ALU subtracts B = 0111 (7) from A = 0101 (5). Find the result and all four flags, and say what the flags conclude about A < B, signed and unsigned.

::: solution
1. **Add $0101 + 1000 + 1$ bit by bit.**

| Bit | Sum | Carry out |
|---|---|---|
| 0 | 0 | 1 |
| 1 | 1 | 0 |
| 2 | 1 | 0 |
| 3 | 1 | 0 |

2. **Read the result.** The result is 1110 = −2.
3. **Set the flags.** $c_4 = 0$ and $c_3 = 0$, so C = 0 and V = 0; N = 1 and Z = 0.
4. **Unsigned comparison.** C = 0 means a borrow, so $5 < 7$.
5. **Signed comparison.** $N \oplus V = 1$, so $5 < 7$ again.
6. **Why they agree.** Both agree here because neither number has its top bit set.

**Answer:** the result is 1110 (−2), with C = 0, V = 0, N = 1 and Z = 0; both comparisons say A < B.
:::
:::

::: example
## Now subtract B = 0111 (+7) from A = 1000 (−8 signed, 8 unsigned). Find the flags and the comparisons.

::: solution
1. **Add $1000 + 1000 + 1$ bit by bit.** Only bit 3 carries: $1 + 1 = 0$ carry 1.

| Bit | Sum | Carry out |
|---|---|---|
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 2 | 0 | 0 |
| 3 | 0 | 1 |

2. **Set the flags.** The result is 0001 with a carry out: $c_4 = 1$ and $c_3 = 0$, so C = 1, V = 1, N = 0 and Z = 0.
3. **Unsigned comparison.** C = 1, no borrow, so $8 \ge 7$: right.
4. **The signed result.** The result 0001 = +1 is wrong, since −8 − 7 = −15 doesn't fit in 4 bits, and V flags it.
5. **Signed comparison.**
   $$\begin{aligned} N \oplus V &= 0 \oplus 1 \\ &= 1 \end{aligned}$$
   says $-8 < 7$: right.
6. **Why N alone fails.** Testing N alone would have said $-8 \ge 7$.

**Answer:** C = 1, V = 1, N = 0 and Z = 0. Unsigned, C = 1 says $8 \ge 7$; signed, $N \oplus V = 1$ says $-8 < 7$. Both are right.
:::
:::

::: example
## A 32-bit ripple-carry ALU uses gates of 20 ps. The carry takes two gate delays per bit, the output multiplexer two more, and the zero flag a tree of 2-input NORs and ANDs after that. How long until Z is valid? What does a 4-input gate tree save?

::: solution
1. **Carry chain.**
   $$\begin{aligned} t &= 32 \times 2 \times 20\ \text{ps} \\ &= 1280\ \text{ps} \end{aligned}$$
2. **Multiplexer.** Two more gate delays: 40 ps.
3. **Zero detector.** It combines 32 bits in $\log_2 32$ = 5 levels: 100 ps.
4. **Total.**
   $$1280 + 40 + 100 = 1420\ \text{ps}$$
5. **With 4-input gates.** The tree takes $\lceil\log_4 32\rceil$ = 3 levels, 60 ps, saving 40 ps, about 3%.
6. **Where the time goes.** The carry chain is 90% of the delay, which is the case for lookahead.

**Answer:** Z is valid after 1420 ps; a 4-input gate tree saves 40 ps, about 3%.
:::
:::

::: check
given: A = 0..15 int; B = 0..15 int
answer: A - B + 16 - 16*floor((A - B + 16)/16)
base: 2
width: 4

## A 4-bit ALU computes A − B for A = {A:bin4} and B = {B:bin4}. What 4-bit result does it produce?

::: right
Right: {answer}, which is $A + \bar B + 1$ with the carry out discarded.
:::

::: misses
- [any] Not yet. Invert B, add 1, add A, and keep the low four bits.
:::
:::

::: check
given: A = 8..15 int; B = 1..7 int
answer: A - B
base: 2
width: 4

## A 4-bit ALU subtracts B = {B:bin4} from A = {A:bin4}. Signed, A is negative and B positive. What result does it produce? (The V flag will say whether it's wrong.)

::: right
Right: {answer}. If its sign bit is 0, the true difference didn't fit, and V = 1.
:::

::: misses
- [any] Not yet. Compute $A + \bar B + 1$ and keep four bits.
:::
:::

::: check
kind: boolean
vars: N, V
answer: N & ~V | ~N & V
ops: and, or, not

## After computing A − B, write the signed less-than condition from the N and V flags, using AND, OR and NOT.

::: right
Right. $N \oplus V$: the sign of the result, corrected when the subtraction overflowed.
:::

::: misses
- [N] N alone is wrong whenever the subtraction overflows.
- [any] Not yet. The result's sign tells you, unless V says the sign is wrong.
:::
:::

::: check
kind: boolean
vars: R3, R2, R1, R0
answer: ~R3 & ~R2 & ~R1 & ~R0
ops: and, or, not

## Write the zero flag of a 4-bit result.

::: right
Right. A NOR of all the bits: 1 only when every bit is 0.
:::

::: misses
- [~(R3 & R2 & R1 & R0)] That's 1 unless every bit is 1. Zero needs every bit 0.
- [any] Not yet. Z = 1 exactly when all four bits are 0.
:::
:::

::: check
kind: boolean
vars: Op1, Op0, B
answer: B & ~(Op1 & Op0) | ~B & Op1 & Op0
ops: and, or, not

## In the play's ALU, Op1 Op0 = 11 means subtract. Write the slice's adder input $x$, which is B for every other operation and $\bar B$ when subtracting.

::: right
Right. $x = B \oplus (Op_1Op_0)$: an XOR gate controlled by the subtract signal.
:::

::: misses
- [B & ~Op0 | ~B & Op0] That would invert B for OR (01) as well. Only 11 subtracts.
- [any] Not yet. Invert B only when both Op bits are 1.
:::
:::

::: check
given: n = 8 | 16 | 32 | 64; t = 10 | 15 | 25
answer: (2*n + 2 + ceil(log(n)/log(2)))*t
unit: ps
tolerance: 0.5%

## An {n}-bit ripple ALU has gates of {t} ps: two gate delays per bit of carry, two for the output multiplexer, then a zero detector built as a tree of 2-input gates. How long until Z is valid?

::: right
Right. $(2n + 2 + \log_2 n)t$ = {answer}.
:::

::: misses
- [(2*n + 2)*t] Add the zero detector's $\log_2 n$ levels.
- [(2*n + 2 + n)*t] A tree combines the bits in $\log_2 n$ levels, not $n$.
- [any] Not yet. Carry chain $2nt$, multiplexer $2t$, tree $t\log_2 n$.
:::
:::

::: check
kind: choice

## Computing A − B on 8 bits sets C = 1, N = 1, V = 1, Z = 0. Which is true?

- [x] Unsigned, A ≥ B; signed, A ≥ B
- [ ] Unsigned, A < B; signed, A < B
- [ ] Unsigned, A ≥ B; signed, A < B
- [ ] Unsigned, A < B; signed, A ≥ B

::: right
Right. C = 1 means no borrow, so unsigned A ≥ B. $N \oplus V = 0$, so signed A ≥ B too: the negative-looking result is an overflow, and the true difference is positive.
:::

::: misses
- [2] C = 1 means no borrow: unsigned A ≥ B.
- [3] Check $N \oplus V$, not N: here it's 0.
- [4] C = 1 means no borrow; and $N \oplus V = 0$.
:::
:::

::: check
kind: python
given: n = 8 | 16 | 32

## Write `alu(a, b, op)` for an `n`-bit ALU ({n} bits), with `op` one of `'and'`, `'or'`, `'add'`, `'sub'`, taking unsigned inputs below $2^n$ and returning `(r, z, neg, c, v)`: the result and the four flags as 0 or 1, computed the way hardware does (subtract as $a + \bar b + 1$; C is the carry out of the top bit; V from the carries into and out of the top bit; logic operations clear C and V). Then write `signed_lt(a, b)` and `unsigned_lt(a, b)` using only the flags from `alu(a, b, 'sub')`.

```python starter
def alu(a, b, op):
    r = (a - b) % (1 << n) if op == 'sub' else (a + b) % (1 << n)
    return r, int(r == 0), r >> (n - 1), 0, 0
def signed_lt(a, b):
    return alu(a, b, 'sub')[2]
def unsigned_lt(a, b):
    return int(a < b)
```

```python solution
M = (1 << n) - 1
def alu(a, b, op):
    if op in ('and', 'or'):
        r = a & b if op == 'and' else a | b
        return r, int(r == 0), r >> (n - 1), 0, 0
    x = b ^ M if op == 'sub' else b
    cin = 1 if op == 'sub' else 0
    total = a + x + cin
    r = total & M
    c = total >> n
    low = (a & (M >> 1)) + (x & (M >> 1)) + cin
    c_into = low >> (n - 1)
    return r, int(r == 0), r >> (n - 1), c, c ^ c_into
def signed_lt(a, b):
    r, z, neg, c, v = alu(a, b, 'sub')
    return neg ^ v
def unsigned_lt(a, b):
    return 1 - alu(a, b, 'sub')[3]
```

```python tests
import random
rng = random.Random(7)
M = (1 << n) - 1
sv = lambda x: x - (1 << n) if x >> (n - 1) else x
for _ in range(2000):
    a, b = rng.randrange(1 << n), rng.randrange(1 << n)
    r, z, neg, c, v = alu(a, b, 'add')
    assert r == (a + b) & M and c == int(a + b > M), f"add {a}, {b}: result or carry is wrong."
    assert v == int(not (-(1 << (n - 1)) <= sv(a) + sv(b) < (1 << (n - 1)))), f"add {a}, {b}: V should flag signed overflow."
    r, z, neg, c, v = alu(a, b, 'sub')
    assert r == (a - b) & M and z == int(a == b) and neg == r >> (n - 1), f"sub {a}, {b}: result or Z, N is wrong."
    assert c == int(a >= b), f"sub {a}, {b}: C should be 1 exactly when no borrow is needed."
    assert v == int(not (-(1 << (n - 1)) <= sv(a) - sv(b) < (1 << (n - 1)))), f"sub {a}, {b}: V should flag signed overflow."
    assert signed_lt(a, b) == int(sv(a) < sv(b)), f"signed_lt({a}, {b}) is wrong."
    assert unsigned_lt(a, b) == int(a < b), f"unsigned_lt({a}, {b}) is wrong."
    assert alu(a, b, 'and')[0] == a & b and alu(a, b, 'or')[0] == a | b, "and/or results are wrong."
```

::: right
Right. Two thousand random pairs confirm the two comparison rules: unsigned less-than is "borrow", and signed less-than is $N \oplus V$, never N alone.
:::
:::

::: explain
## A programmer tests whether a signed 8-bit temperature is below a threshold by subtracting and checking only the sign of the result. It works in testing but fails for a reading of −100 against a threshold of 50. Explain using the ALU's flags.

::: model
The true difference, −100 − 50 = −150, doesn't fit in 8 bits, whose signed range is −128 to 127. The ALU's subtraction wraps around to +106, so the sign bit N is 0 and the test says −100 is not below 50. The ALU also sets the overflow flag V, because the carries into and out of the sign bit differ, which means the sign bit is wrong. The correct signed less-than test is $N \oplus V$, which here is 1, and that's what a signed comparison or a signed branch instruction checks. The bug only shows when the operands are far apart with opposite signs, which is why ordinary test values missed it.
:::
:::

::: practice

::: check
given: A = 0..15 int; B = 0..15 int
answer: A + B - 16*floor((A + B)/16)
base: 2
width: 4

## A 4-bit ALU adds {A:bin4} and {B:bin4}. What result does it produce?

::: misses
- [any] Add and keep the low four bits.
:::
:::

::: check
given: n = 16 | 32 | 64 | 128
answer: ceil(log(n)/log(4))
tolerance: 0.5%

## How many levels of 4-input gates does a tree need to combine {n} bits into one zero flag?

::: misses
- [ceil(log(n)/log(2))] With 4-input gates, each level combines four signals.
- [any] $\lceil\log_4 n\rceil$.
:::
:::
:::
