In: Electrical Engineering
Design of 4 Bit Adder/Subtractor using Loops (Behavior Modeling Style) (verilog Code) -
if a_s = 0 then it will act as adder and for a_s = 1 will act as subtractor
VERILOG CODE:
module adder_sub_4bit ( a ,b ,sum_diff ,carry_borrow,a_s );
output reg [3:0] sum_diff ;
output reg carry_borrow ;
input [3:0] a ;
input [3:0] b ;
input a_s;
wire [3:0]l;
assign l = ~ b;
integer i;
reg [4:0]s;
always @ (a or b) begin
if (a_s == 1'b0)
begin
s[0] = 0;
for
(i=0;i<=3;i=i+1) begin
sum_diff [i] = a[i] ^ b[i] ^ s[i];
s[i+1] = (a[i] & b[i]) | (b[i] & s[i]) |
(s[i] & a[i]);
end
carry_borrow =
s[4];
end
else begin
s[0] = 1;
for (i=0;i<=3;i=i+1) begin
sum_diff[i] =
a[i] ^ l[i] ^ s[i];
s[i+1] = (a[i]
& l[i]) | (l[i] & s[i]) | (s[i] & a[i]) ;
end
carry_borrow = ~s[4];
end
end
endmodule
TEST BENCH:
module tb_add_sub;
// Inputs
reg [3:0] a;
reg [3:0] b;
reg a_s;
// Outputs
wire [3:0] sum_diff;
wire carry_borrow;
// Instantiate the Unit Under Test (UUT)
adder_sub_4bit uut (
.a(a),
.b(b),
.sum_diff(sum_diff),
.carry_borrow(carry_borrow),
.a_s(a_s)
);
initial begin
// Initialize Inputs
a = 1; b = 3; a_s = 0;
#100 a = 6; b = 3; a_s = 1;
end
endmodule
Simulation Results are