Prev Problem
Next Problem

69. Binary Subtractor

Back To All Submissions
Previous Submission
Next Submission

Solving Approach

How do you plan to solve it?

 

Code

module half_adder (
    input  a, b,
    output sum, carry
);
    // Write code here
    assign sum   = a ^ b;
    assign carry = a & b;
endmodule

module full_adder_1bit (
    input  a, b, cin,
    output sum, cout
);
    // TODO: implement 1-bit full adder (structural or dataflow)
    wire sum1, carry1, carry2;
    // Write code here
    half_adder ha1 (.a(a),    .b(b),   .sum(sum1), .carry(carry1));
    half_adder ha2 (.a(sum1), .b(cin), .sum(sum), .carry(carry2));
    assign cout = carry1 | carry2;
endmodule

module rca4_add (
    input  [3:0] x, y,
    input        cin,
    output [3:0] sum,
    output       cout
);
    wire c1, c2, c3;
    full_adder_1bit fa0(.a(x[0]), .b(y[0]), .cin(cin), .sum(sum[0]), .cout(c1));
    full_adder_1bit fa1(.a(x[1]), .b(y[1]), .cin(c1 ), .sum(sum[1]), .cout(c2));
    full_adder_1bit fa2(.a(x[2]), .b(y[2]), .cin(c2 ), .sum(sum[2]), .cout(c3));
    full_adder_1bit fa3(.a(x[3]), .b(y[3]), .cin(c3 ), .sum(sum[3]), .cout(cout));
endmodule

module sub4_2c (
    input  [3:0] a,
    input  [3:0] b,
    output [3:0] diff,
    output       bout
);
    wire [3:0] b_inv = ~b;
    wire       cout;
    rca4_add adder(.x(a), .y(b_inv), .cin(1'b1), .sum(diff), .cout(cout));
    assign bout = ~cout;
endmodule

 

Was this helpful?
Upvote
Downvote