4 bit adder-subtractor in verilog

Subhadip picture Subhadip · Sep 2, 2018 · Viewed 23.4k times · Source

I am writing verilog code for 4 bit adder subtractor. I am using structural design. At first I have written verilog code for 1 bit full adder. Then I am using that to write code for 4 bit adder subtractor .

module fadder (A, B, Cin, Sum, Cout);
    input A, B;
    input Cin;
    output Sum;
    output Cout;
    wire t1,t2,t3,t4;
  xor x1(t1,A,B);
  xor x2(Sum,t1,Cin);
  and g1(t2,A,B);
  and g2(t3,B,Cin);
  and g3(t4,Cin,A);
  or  g4(Cout,t2,t3,t4);  
endmodule


module add_sub_4 (A, B, In, Res, Out);
    input [3:0] A, B;
    input In;
    output [3:0] Res;
    output Out;
    wire t1,t2,t3,t4,t5,t6,t7;


          xor x3(t3,B[0],In);
          xor x4(t4,B[1],In);
          xor x5(t5,B[2],In);
          xor x6(t6,B[3],In);
          fadder f5(A[0],t3,In,Res[0],t1);
          fadder f6(A[1],t4,t1,Res[1],t2);
          fadder f7(A[2],t5,t2,Res[2],t3);
          fadder f8(A[3],t6,t3,Res[3],Out);  
endmodule

Answer

dustinwerran picture dustinwerran · Sep 2, 2018

You're actually pretty close. What you seem to not understand is that in Verilog your design is synthesized at compile time, not at run time. You can't instantiate modules conditionally because at compile time we don't know if that condition will be met or not. So your first statement in the case of the subtraction bit being low doesn't really make sense. It also doesn't make sense to put it in an always block, since the rtl is defined in the modules already.

However, your second statement contains most of the solution to the problem. When the sign bit is low, those xors at the top of the adder/subtractor will preserve the incoming bits, and the design will simplify to just an adder. Try just using the second block alone.