4-bit Adder-Subtractor

Description:

A 4-bit adder-subtractor is a digital circuit that can perform both addition and subtraction of two 4-bit binary numbers. It uses a control signal (AddSub) to select the operation. When AddSub = 0, it performs addition; when AddSub = 1, it performs subtraction.

Block Diagram:

<span class="selected">      A[3:0] ----|
                 |
      B[3:0] ----|-----> XOR Gates ----|
                 |                     |
      AddSub ----|                     |
                 |                     |-----> 4-bit Adder ----> Sum[3:0]
                                       |
                                       |-----> CarryOut
</span><br class="ProseMirror-trailingBreak" />

Where:

  • A[3:0] and B[3:0] are the two 4-bit input numbers.
  • AddSub is the control signal:
    • 0 for addition (B is directly added to A)
    • 1 for subtraction (B is inverted and 1 is added to A via CarryIn, performing 2’s complement subtraction)
  • XOR Gates invert B when AddSub = 1.
  • 4-bit Adder performs the addition.
  • Sum[3:0] is the 4-bit result.
  • CarryOut is the final carry-out.

Verilog Code:

<span class="selected">module adder_subtractor_4bit(
  input  [3:0] A,
  input  [3:0] B,
  input        AddSub,
  output [3:0] Sum,
  output       CarryOut
);

  wire [3:0] B_modified;
  wire       CarryIn;

  // Modify B based on AddSub
  assign B_modified[0] = B[0] ^ AddSub;
  assign B_modified[1] = B[1] ^ AddSub;
  assign B_modified[2] = B[2] ^ AddSub;
  assign B_modified[3] = B[3] ^ AddSub;

  // Carry-in for the adder
  assign CarryIn = AddSub;  // If AddSub is 1, it's subtraction (add 1 for 2's complement)

  // Instantiate the 4-bit ripple carry adder
  ripple_carry_adder_4bit adder(
    .A(A),
    .B(B_modified),
    .Cin(CarryIn),
    .Sum(Sum),
    .Cout(CarryOut)
  );

endmodule
</span><br class="ProseMirror-trailingBreak" />

Test Bench Code:

<span class="selected">module adder_subtractor_4bit_tb;
  reg  [3:0] A, B;
  reg         AddSub;
  wire [3:0] Sum;
  wire        CarryOut;

  adder_subtractor_4bit as_test(
    .A(A),
    .B(B),
    .AddSub(AddSub),
    .Sum(Sum),
    .CarryOut(CarryOut)
  );

  initial begin
    // Addition
    AddSub = 0;
    A = 4'b0000; B = 4'b0000; #10;
    A = 4'b0001; B = 4'b0010; #10;
    A = 4'b0101; B = 4'b0110; #10;
    A = 4'b1010; B = 4'b1011; #10;
    A = 4'b1111; B = 4'b1111; #10;

    // Subtraction
    AddSub = 1;
    A = 4'b0000; B = 4'b0000; #10;
    A = 4'b0001; B = 4'b0010; #10;
    A = 4'b0101; B = 4'b0110; #10;
    A = 4'b1010; B = 4'b1011; #10;
    A = 4'b1111; B = 4'b1111; #10;
    $finish;
  end

  initial begin
    $monitor("AddSub=%b, A=%b, B=%b, Sum=%b, CarryOut=%b", AddSub, A, B, Sum, CarryOut);
  end

endmodule
</span>
Scroll to Top