Alan
Alan

Reputation: 43

How to create 2's Complement Adder in Verilog?

This is the ripple carry adder that is being used, however, when the sub = 1 A = 4 B = 3, the program is returning no overflow and the sum is 1100 instead of 0110. Have we messed up the carry behavior?

module fullAdder(A, B, Cin, sum, Cout);
    input A, B, Cin;
    output sum, Cout;
    assign sum = A^B^Cin;
    assign Cout = (Cin&A) | (Cin&B) |(A&B);
endmodule


module RCA4bit(A, B, C0, sum, C1, overflow);
    input [3:0] A;
    input [3:0] B;
    output [3:0] sum;
    input C0;
    output C1;
    output overflow;
     wire [2:0] carry;
     fullAdder RCA1(A[0], B[0], C0, sum[0], carry[0]);
     fullAdder RCA2(A[1], B[1], carry[0], sum[1], carry[1]);
     fullAdder RCA3(A[2], B[2], carry[1], sum[2], carry[2]);
     fullAdder RCA4(A[3], B[3], carry[2], sum[3], C1);
     assign overflow = C1 ^ carry[2];
endmodule

module RCA4bit2cmp(A, B, sub, sum, C1, overflow);
   input [3:0] A;
   input [3:0] B;
   output [3:0] sum;
   input sub;
   output C1;
   output overflow;

    wire [3:0]invB;
    assign invB = sub?~B:B;

    RCL4bit RC4(A, invB, sub, sum, C1, overflow);

endmodule

Upvotes: 1

Views: 5553

Answers (1)

Tim
Tim

Reputation: 35933

Your overflow term doesn't make sense to me, I would think overflow would just be the carry out, I don't know why you've xor'd it with carry[2].

Other that that I don't see anything wrong, I don't see how that could be giving 1100 as an output, and I don't see why you expect the answer to be 0110 (6).

If A is 0100, and b is 0011, than invB is 1100, plus the extra Cin means that B you've got:

  0100   (A)
  1100   (invB)
+ 0001   (Cin)
_________
 10001  

Overflow is 1, and the result is 0001 (4-3 = 1).

Have you tried inspecting via waveform to see where your results diverge from this?

Upvotes: 1

Related Questions