Medium · Arithmetic · SystemVerilog Constructs
Implement a combinational 8-bit ALU with eight operations and three status flags.
| Port | Dir | Width | Meaning |
|---|---|---|---|
a | input | 8 | First operand. |
b | input | 8 | Second operand (for shifts, only b[2:0] is used). |
op | input | 3 | Operation select (table below). |
y | output | 8 | Result. |
zero | output | 1 | 1 when y == 0, for every operation. |
carry | output | 1 | Unsigned carry (ADD) or borrow (SUB); 0 for all other ops. |
overflow | output | 1 | Signed (two's-complement) overflow for ADD/SUB; 0 for all other ops. |
The ALU is purely combinational: all outputs follow the inputs with no clock.
op | Name | y | |
|---|---|---|---|
| 0 | ADD | a + b (low 8 bits) | |
| 1 | SUB | a - b (low 8 bits) | |
| 2 | AND | a & b | |
| 3 | OR | `a \ | b` |
| 4 | XOR | a ^ b | |
| 5 | SLT | 8'd1 if a < b when both are read as signed two's-complement numbers (−128…127), else 8'd0 | |
| 6 | SLL | a shifted left by b[2:0] (0–7) bits, zeros shifted in | |
| 7 | SRA | a shifted right arithmetically by b[2:0] bits: copies of a[7] (the sign bit) are shifted in |
zero = (y == 8'd0) for all eight operations (so SLT with a false result sets zero).carry:a + b, i.e. 1 iff a + b > 255 (unsigned).1 iff a < b when both are read as unsigned numbers.(Note: this is the x86-style borrow. Some CPUs, such as ARM, define the carry of a subtraction as the inverse; here it is the borrow.)
0.overflow (operands and result read as signed 8-bit numbers):1 iff the true sum a + b is outside −128…127. Equivalently: a and b havethe same sign and y has a different sign.
1 iff the true difference a − b is outside −128…127. Equivalently: a and bhave different signs and y's sign differs from a's.
0.op | a | b | y | zero | carry | overflow |
|---|---|---|---|---|---|---|
| 0 ADD | 8'h7F | 8'h01 | 8'h80 | 0 | 0 | 1 |
| 0 ADD | 8'hFF | 8'h01 | 8'h00 | 1 | 1 | 0 |
| 1 SUB | 8'h05 | 8'h07 | 8'hFE | 0 | 1 | 0 |
| 1 SUB | 8'h80 | 8'h01 | 8'h7F | 0 | 0 | 1 |
| 5 SLT | 8'hFF | 8'h01 | 8'h01 | 0 | 0 | 0 |
| 7 SRA | 8'h90 | 8'h02 | 8'hE4 | 0 | 0 | 0 |
| 6 SLL | 8'h81 | 8'h0C | 8'h10 | 0 | 0 | 0 |
In the SLT row, 8'hFF is −1, which is less than 1. In the SRA row, 8'b1001_0000 >>> 2 = 8'b1110_0100. In the SLL row, only b[2:0] = 3'd4 counts (the upper bits of b are ignored), so 8'b1000_0001 << 4 = 8'b0001_0000.
typedef enum logic [2:0] { OP_ADD = 3'd0, OP_SUB, ... } op_e;inside the module and switch on op_e'(op) (a cast) in a case. The port itself stays a plain logic [2:0], because the testbench drives it as a number.
{1'b0, a} + {1'b0, b}.>>> only shifts in sign bits when its left operand is signed. a is unsigned, soa >>> n behaves exactly like a >> n. Use $signed(a) >>> n.
a < b on unsigned operands is an unsigned comparison; use $signed(...).always_comb so every flag isdefined for every op.
Sign up free to solve 8-bit ALU with Flags in your browser.