What is an ALU
In the last lesson we saw the "add" instruction. But who actually does the adding? And who handles subtraction and comparison? Let's meet the worker inside the CPU that does nothing but calculate: the ALU.
A part that only calculates
Inside the CPU there's a part that does nothing but calculate. It's called the ALU.
Give it two numbers and "which calculation to do," and it does that calculation and puts out the result.
It's like the heart of a calculator.
Two numbers go in at the top, and the result comes out at the bottom.
ALU is short for "arithmetic logic unit."
The name sounds grand, but the job is clear.
It does the requested calculation on the two numbers it receives, and that's all it does.
Pick the kind of calculation with a dial
The ALU is useful because it doesn't do just one kind of calculation.
Turn the "which calculation" dial to add, subtract, or multiply, and the same two numbers give different results.
Below, you can enter two numbers and change the dial.
Enter two numbers and pick a calculation.
Only the dial changed, yet the same worker did a different calculation.
This "which calculation" is actually a value set by the instruction from the last lesson.
The adder from Lesson 6 lives here
Open up the ALU and you'll find something familiar: the adder we built in Lesson 6.
That adder handles addition, and small circuits for subtraction, comparison, and logic operations like AND and OR all live together here.
The calculating circuits gathered inside the ALU.
The small circuits we built one by one in Lessons 5 and 6 were actually parts of this ALU.
Small pieces came together to make one calculating worker.
The ALU also answers "which is bigger?"
Among the ALU's jobs, comparison matters as much as calculation.
It answers questions like "Is this number bigger than that one?" or "Are the two numbers equal?" with true or false.
That single true or false later becomes the seed of a fork in the road called "if."
True is 1, false is 0. To a computer, this is 0s and 1s too.
The answer to "Is 10 bigger than 7?" is true.
This simple judgment is hugely important.
Every time a program looks at a situation and chooses a path, it starts with a comparison like this.
The instruction turns the dial
Now the two stories meet.
The front part of an instruction from the last lesson, the opcode, is what turns the ALU's dial.
"Add" sets the dial to addition; "subtract" sets it to subtraction.
In other words, the kind of calculation the ALU should do is written inside the instruction.
The instruction's opcode → the ALU's dial.
The instruction decides what to do, and the ALU carries out the calculation.
With that, two core parts of the CPU are in place.
In the next lesson, we'll look at the whole CPU and see how these two work as one.