Hardware interview practice
Implement Signed Eight-Bit Add/Subtract with Overflow
A combinational ALU adds or subtracts two signed 8-bit two's-complement operands. The 8-bit result wraps modulo 256, and a separate flag reports mathematical overflow outside -128 through 127. Implement addition/subtraction and the exact signed overflow flag without using a wider saturated result.
Starting point
Question code
module addsub8(input logic signed [7:0] a,b, input logic sub,
output logic signed [7:0] y, output logic overflow);
// sub=0: a+b; sub=1: a-b
// combinational; wrapped two's-complement yReviewed example
Work through one case
Input
Case 1: a=127,b=1,sub=0
Case 2: a=-128,b=1,sub=1
Case 3: a=50,b=20,sub=1Expected output
Case 1: y=-128 (8'h80), overflow=1.
Case 2: y=127 (8'h7F), overflow=1.
Case 3: y=30, overflow=0.The shown result follows by applying this rule: Wrapped arithmetic and the add/sub selection match two's-complement behavior. The cases also demonstrate this requirement: Drive outputs for every input combination without latches and verify all 131,072 `(a,b,sub)` combinations against a signed 9-bit reference range check.
What to cover
Requirements
- Compute `y=a+b` for sub=0 and `y=a-b` for sub=1 with an 8-bit wrapped result.
- For addition, overflow is true when a and b have the same sign and y has the opposite sign.
- For subtraction, overflow is true when a and b have different signs and y has a sign different from a.
- Drive outputs for every input combination without latches and verify all 131,072 `(a,b,sub)` combinations against a signed 9-bit reference range check.
