8-bit ALU with Flags

Medium · Arithmetic · SystemVerilog Constructs

Implement a combinational 8-bit ALU with eight operations and three status flags.

Ports

PortDirWidthMeaning
ainput8First operand.
binput8Second operand (for shifts, only b[2:0] is used).
opinput3Operation select (table below).
youtput8Result.
zerooutput11 when y == 0, for every operation.
carryoutput1Unsigned carry (ADD) or borrow (SUB); 0 for all other ops.
overflowoutput1Signed (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.

Operations

opNamey
0ADDa + b (low 8 bits)
1SUBa - b (low 8 bits)
2ANDa & b
3OR`a \b`
4XORa ^ b
5SLT8'd1 if a < b when both are read as signed two's-complement numbers (−128…127), else 8'd0
6SLLa shifted left by b[2:0] (0–7) bits, zeros shifted in
7SRAa shifted right arithmetically by b[2:0] bits: copies of a[7] (the sign bit) are shifted in

Flags, precisely

(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.)

the same sign and y has a different sign.

have different signs and y's sign differs from a's.

Examples

opabyzerocarryoverflow
0 ADD8'h7F8'h018'h80001
0 ADD8'hFF8'h018'h00110
1 SUB8'h058'h078'hFE010
1 SUB8'h808'h018'h7F001
5 SLT8'hFF8'h018'h01000
7 SRA8'h908'h028'hE4000
6 SLL8'h818'h0C8'h10000

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.

SystemVerilog tips

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.

a >>> n behaves exactly like a >> n. Use $signed(a) >>> n.

defined for every op.

Sign up free to solve 8-bit ALU with Flags in your browser.

More Arithmetic problems