A 4-bit arithmetic logic unit
The problem
Build a software model of a small arithmetic logic unit (ALU), made only from gate functions, that adds, subtracts, ANDs, ORs and compares two 4-bit numbers, and reports the flags.
Requirements
- Write functions for NOT, AND, OR, XOR, NAND and NOR on single bits, and build every other part from them
- Build a full adder, a 4-bit ripple-carry adder and a subtractor with one adder and an XOR on each B input
- Add a multiplexer that picks the operation from a 2-bit code
- Report the carry out, the signed overflow and the zero flag for each result
Technologies
- Python
- Bit operations
- Truth tables
Step by step
- Write the single-bit gate functions and test them against their truth tables.
- Build the full adder from gates, and chain four of them into an adder.
- Add the XOR gates and the carry in to make the subtractor.
- Add the multiplexer that selects ADD, SUB, AND or OR, and compute the flags.
- Test the ALU on all 256 pairs of inputs against Python's own arithmetic and bit operators.
Expected result
A program in which every one of the 256 input pairs gives the right result and flags for all four operations.
How it is evaluated
- No operator other than the gate functions is used inside the ALU
- All 256 input pairs match the reference for every operation
- Carry and signed overflow are reported separately and correctly
Ways to improve it
- Widen the ALU to 8 bits
- Add shifts and a comparator output
- Replace the ripple-carry adder with a carry-lookahead adder and compare the path delays