Search code examples
verilog

Getting wrong output for 4x4 multiplier


module fa(
input a,b,cin,
output reg s,cout
);

always@(*) begin
    s = a^b^cin;
    cout = (a & b) | (b & cin) | (cin & a);
end

endmodule

module multiplier(
input [3:0] a,b,
output [7:0] p
);

wire w01,w10,w20,w11,w02,w30,w21,w12,w03,w31,w22,w13,w32,w23,w33,s1,s2,s3,s4,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10;

assign p[0] = a[0] & b[0];

assign w01 = b[0] & a[1];
assign w10 = b[1] & a[0];
assign w20 = b[2] & a[0];
assign w11 = b[1] & a[1];
assign w02 = b[0] & a[0];
assign w30 = b[3] & a[0];
assign w21 = b[2] & a[1];
assign w12 = b[1] & a[2];
assign w03 = b[0] & a[3];
assign w31 = b[3] & a[1];
assign w22 = b[2] & a[2];
assign w13 = b[1] & a[3];
assign w32 = b[3] & a[2];
assign w23 = b[2] & b[3];
assign w33 = b[3] & a[3];

fa g1(w01,w10,1'b0,p[1],c1);
fa g2(w20,w11,c1,s1,c2);
fa g3(s1,w02,c2,p[2],c3);
fa g4(w30,w21,c3,s2,c4);
fa g5(s2,w12,c4,s3,c5);
fa g6(s3,w03,c5,p[3],c6);
fa g7(w31,w22,c6,s4,c7);
fa g8(s4,w13,c7,p[4],c8);
fa g9(w32,w23,c8,p[5],c9);
fa g10(w33,c9,1'b0,p[6],c10);

assign p[7] = c10;

endmodule

module multiplier_tb;

reg [3:0] a,b;
wire [7:0] p;
integer cnt1,cnt2;

multiplier dut(a,b,p);

initial begin
    for(cnt1 = 0;cnt1<16;cnt1 = cnt1 + 1) begin
        for(cnt2 = 0;cnt2<16;cnt2 = cnt2 + 1) begin
            {a} = cnt1;
            {b} = cnt2;
            #10;
        end
    end
end

endmodule

I tried debugging the code multiple times for logical errors ,still not able to find it. I am asked to implement a 4x4 multiplier using full adders in behavioural modeling. I think main logic is correct and that I am missing to add a carry somewhere. i wrote down the bits to be multiplied and added them using full adders. I am getting wrong output for testcase such as 15x15 where i get an output of 189.

My Design design

my idea is to add all terms using full adders and add the carry that come while doing so


Solution

  • your logical issue is the following is in that you add bits in columns. Think about what will happen if you add the following:

      1     s  cout
    + 1 --> 0   1
    + 1 --> 0,  1
    + 1 --> 0,  1
    ====
      0, cout 1 !!!
    

    in reality you are supposed to have at least a two bit cout (10) to get 100 as a result.

    So, either you came up with a clever algorithm to handle a multi-bit cout and passing it on to the next columns or you just do line-wise additions:

      01 << w1
    + 01 << w2
    ====
      10 << s1
    + 01 << w3
    ====
      11 << s2
    + 01 << w3
    ====
     100 << s3