04Implementation
Keep the carry out of an adder
Problem
Intended behavior. adder4 adds two 4-bit inputs and drives a 5-bit sum.
The largest result, 15 + 15 = 30, needs five bits, so the top bit of sum is
the carry out of the addition.
Current behavior. The starter compiles and 3 + 4 prints 7, but 9 + 8
prints 1 and 15 + 15 prints 14. Every result above 15 loses exactly 16.
Your task. Rewrite the marked assign so that all five bits of sum hold the
true sum. Keep the port list and the public testbench as they are.
Read and predict
The starter builds sum from a constant 1'b0 and the expression a + b inside
braces. Inside a concatenation each operand is evaluated at its own width, and
a + b with two 4-bit operands is a 4-bit result there. Work out what 9 + 8
becomes in four bits, then place a zero above it. The result should match the
printed 1.
Now predict all three rows for a correct adder. The difference between your two predictions shows which bit is being thrown away and where. The expression-width example in the Module chapter traces the same rule on an average.
Rewrite only the marked assign, run again, and check that the two larger rows
now print 17 and 30. Then explain which part of the old line decided the width
of the addition, and why the 5-bit sum port alone could not widen it.
Completion check
sumequalsa + bfor all 256 input pairs, from 0 + 0 to 15 + 15.- Results from 16 to 30 show the carry in bit 4 instead of a forced zero.
adder4keeps its port names and widths.
Progressive hints
Hint 1
The bits are not lost by the addition itself; they are lost because of the width at which the addition is evaluated.
Hint 2
Outside braces, Verilog sizes an addition from the widest operand and the destination of the assignment. A 5-bit destination gives the addition room for its carry.
Hint 3
The constant zero in the concatenation is the part that forces bit 4 low. Ask whether the concatenation is needed at all.
Transfer experiment
Imagine sum were only four bits wide but you still wanted to know whether the
addition overflowed. Describe what extra output port you would add, and which
bit of a wider internal result it would carry.