Search code examples
verilogadditioncalculatorsubtraction

Verilog 2's complement adder/subtractor


Design a four-bit adder/subtractor in Verilog and display it on a seven-segment display.

The majority of my code is functioning however when I require a subtraction involving a negative it produces the wrong result.

For instance, 5 - 7 should result in 2 but I receive E

Below is my code:

module fullAdder (a0,a1,carry_in,s,carry_out);

    input a0,a1,carry_in;
    output s, carry_out;

    assign s = (a0 ^ a1) ^ carry_in;
    assign carry_out = (a0 & a1 & carry_in)|(a0 & a1 & ~carry_in)|(a0 & ~a1 & carry_in)|(~a0 & a1 & carry_in);

endmodule

module Lab3(a0,a1,s,cout);

    input s;
    input  [3:0] a0, a1;
    output [3:0] cout;
    
    wire c,d,e,f;
    wire input1, input2, input3, input4;
    
    xor(input1, s, a1[0]);
    xor(input2, s, a1[1]);
    xor(input3, s, a1[2]);
    xor(input4, s, a1[3]);
    
    //a0,a1,carry_in,s,carry_out    
    fullAdder fa0(a0[0],input1,s,cout[0],c);
    fullAdder fa1(a0[1],input2,c,cout[1],d);
    fullAdder fa2(a0[2],input3,d,cout[2],e);
    fullAdder fa3(a0[3],input4,e,cout[3],f);

endmodule 

Solution

  • E is the correct result here, as it is -2 in 4 bit two's complement.

    The trick to go from a negative two's complement value to positive, if you haven't covered it already, is to invert and add one.

    • E is 1110 in binary

    • 1110 inverted is 0001

    • 0001 plus 1 is 0010 (2)