Notes for Nand2Tetris: Boolean Arithmetic and the ALU
This is a note for Nand2Tetris Unit 2.
Unit 2.2
Half Adder
Truth table:
a | b | sum | carry |
---|---|---|---|
0 | 0 | 0 | 0 |
0 | 1 | 1 | 0 |
1 | 0 | 1 | 0 |
1 | 1 | 0 | 1 |
Interface:
1 | CHIP HalfAdder { |
Idea:
sum
isa XOR b
carry
isa AND b
Full Adder
Interface:
1 | CHIP FullAdder { |
Unit 2.3
2's complement
2's complement represent negative number $-x$ using the positive number $2^{n}-x$.
- Range of positive numbers: $[0, 2^{n-1}-1]$
- Range of negative numbers: $[-2^{n-1}, -1]$
How to compute -x
How to do this quickly?
$$
Input: x
$$
$$
Output: -x (in 2's complement)
$$
The idea is:
$$
2^{n}-x = 1+(2^{n}-1)-x
$$
where $(2^{n}-1)$ is $n$ bits of ones, and using it to minus $x$ equals to flipping every bit of $x$.
So, the steps to compute -x is:
- Flip every bit of x;
- Plus one.
Unit 2.4
ALU: Arithmetic Logic Unit
Project 2
HalfAdder.hdl
1 | CHIP HalfAdder { |
FullAdder.hdl
Use two HalfAdder
s and a OR
to combine a FullAdder
, per here.
1 | CHIP FullAdder { |
Add16.hdl
1 | CHIP Add16 { |
Inc16.hdl
This is a little tricky.
1 | CHIP Inc16 { |
ALU.hdl
There are so many conditionals in this chip. How to make them? The idea is make all the results first, then choose the result we what using Mux
.
1 | /** |