Concept Flow - Adder and subtractor design
Input A, Input B, Control
Check Control
Perform A+B
Output Result
The design checks a control signal to decide whether to add or subtract two inputs, then outputs the result.
library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; entity AdderSubtractor is port( A, B : in unsigned(3 downto 0); Control : in std_logic; -- 0 for add, 1 for subtract Result : out unsigned(3 downto 0) ); end entity; architecture Behavioral of AdderSubtractor is begin process(A, B, Control) is begin if Control = '0' then Result <= A + B; else Result <= A - B; end if; end process; end Behavioral;
| Step | A | B | Control | Condition | Operation | Result |
|---|---|---|---|---|---|---|
| 1 | 0011 (3) | 0001 (1) | 0 | Control = '0'? | Add A + B | 0100 (4) |
| 2 | 0101 (5) | 0010 (2) | 1 | Control = '0'? | Subtract A - B | 0011 (3) |
| 3 | 1111 (15) | 0001 (1) | 0 | Control = '0'? | Add A + B | 0000 (0) (overflow ignored) |
| 4 | 0010 (2) | 0100 (4) | 1 | Control = '0'? | Subtract A - B | 1110 (14) (underflow, wraps) |
| 5 | - | - | - | - | - | End of simulation |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 | Final |
|---|---|---|---|---|---|---|
| A | 0000 | 0011 | 0101 | 1111 | 0010 | 0010 |
| B | 0000 | 0001 | 0010 | 0001 | 0100 | 0100 |
| Control | 0 | 0 | 1 | 0 | 1 | 1 |
| Result | 0000 | 0100 | 0011 | 0000 | 1110 | 1110 |
VHDL Adder-Subtractor: Use a Control signal to select operation. If Control='0', Result = A + B. If Control='1', Result = A - B. Unsigned arithmetic wraps on overflow/underflow. Process sensitive to inputs and Control.
std_logic_vector represents bits, it does not support arithmetic directly. The unsigned type allows arithmetic operations on bit vectors.unsigned is used to perform arithmetic on bit vectors.signal A, B : unsigned(3 downto 0); signal Result : unsigned(3 downto 0); signal Subtract : std_logic; Result <= A + (B xor (Subtract & Subtract & Subtract & Subtract)) + Subtract;
Subtract = '1'?Result <= A - B; -- A and B are std_logic_vector(3 downto 0)
std_logic_vector, which do not support arithmetic operations directly.unsigned or signed types before subtraction.Sub to select addition (Sub='0') or subtraction (Sub='1'). Which of the following code snippets correctly implements this behavior?Pass the test and this pattern moves unknown