Subtractor
Use two’s complement to express subtraction with an adder, then trace a negative result and the borrow. For four-bit 3 minus 5, the interface’s numeric range determines whether the result bits mean 14 or −2.
The collector subtracts a baseline of five from a reading of three. Its four-bit output is 1110, hexadecimal E. That pattern reads as signed −2 or unsigned fourteen. The receiver also needs the flag that matches its interpretation.
Invert B and add one to make subtraction an addition
Invert four-bit B and add one to form its two’s-complement negation. The circuit computes a + ~b + 1 and keeps the low four bits. For three minus five, the four-bit complement of 5 is hexadecimal A. The addition 3 + A + 1 produces E with no fifth bit.
When unsigned A is below B, this addition has no carry out. The unsigned subtraction needs a borrow, so the RTL inverts the fifth bit to get borrow. Swap the inputs and 5 + ~3 + 1 produces hexadecimal 12. The low result is 2, the fifth bit is one, and no borrow is needed.
Read 8 as four-bit two’s-complement −8 and 8−1 has signed difference −9, outside the range. The low word reads 7 and overflow=1. Unsigned eight minus one gives seven with borrow=0.
Synthesizable SystemVerilog
module subtractor4 (
input logic [3:0] a,
input logic [3:0] b,
output logic [3:0] diff,
output logic borrow,
output logic overflow
);
logic [4:0] wide_diff;
assign wide_diff = {1'b0, a} + {1'b0, ~b} + 5'd1;
assign diff = wide_diff[3:0];
assign borrow = !wide_diff[4];
assign overflow = (a[3] != b[3]) && (diff[3] != a[3]);
endmodule
Check the results against the waveform
Data values are hexadecimal. Control signals and flags are shown separately.
| Change at | a | b | diff | borrow | overflow |
|---|---|---|---|---|---|
| 0 ns | 3 | 5 | E | 1 | 0 |
| 10 ns | 5 | 3 | 2 | 0 | 0 |
| 20 ns | 8 | 1 | 7 | 0 | 1 |
| 30 ns | 0 | 0 | 0 | 0 | 0 |
| 40 ns | 7 | F | 8 | 1 | 1 |
Borrow indicates whether unsigned A was large enough. Signed overflow indicates whether the true signed difference fits four bits. The flags can change independently.
Download the runnable SystemVerilog lab. Icarus checks the 5 rows above and 256 binary input combinations. It reads each directed result 1 ns after changing the inputs. The wait sets an observation time in the testbench. The waveform is functional evidence. Physical delay needs a timing model.
Interactive lab
Compare borrow for 3−5 and 5−3. Then try 8−1, reading 8 as two's-complement −8 for signed overflow.
- Low difference (hex)
- Unsigned borrow
- Signed overflow
Show the last eight observations
Teaching film
Run the RTL yourself
Extract the lab and follow the commands in its README. Compare the simulated outputs and waveform with your predictions from the interactive lab.
Download Subtractor RTL (.zip)