FPGA/HDLBits
Module addsub
장영현
2023. 6. 10. 19:56
728x90
Problem Statement
An adder-subtractor can be built from an adder by optionally negating one of the inputs, which is equivalent to inverting the input then adding 1. The net result is a circuit that can do two operations: (a + b + 0) and (a + ~b + 1). See Wikipedia if you want a more detailed explanation of how this circuit works.
Build the adder-subtractor below.
You are provided with a 16-bit adder module, which you need to instantiate twice:
module add16 ( input[15:0] a, input[15:0] b, input cin, output[15:0] sum, output cout );
Use a 32-bit wide XOR gate to invert the b input whenever sub is 1. (This can also be viewed as b[31:0] XORed with sub replicated 32 times. See replication operator.). Also connect the sub input to the carry-in of the adder.
//성공 코드
module top_module(
input [31:0] a,
input [31:0] b,
input sub,
output [31:0] sum
);
wire [31:0] x;
wire [15:0] sum1, sum2;
wire cout1, cout2;
assign x = b^{32{sub}};
add16 instance1 (a[15:0], x[15:0], sub, sum1, cout1);
add16 instance2 (a[31:16], x[31:16], cout1, sum2, cout2);
assign sum = {sum2, sum1};
endmodule
//실패 코드
module top_module(
input [31:0] a,
input [31:0] b,
input sub,
output [31:0] sum
);
wire [31:0] x;
wire [15:0] sum1, sum2;
wire cout1, cout2;
assign x = b^{32{sub}};
add16 instance1 = (a[15:0], x[15:0], sub, sum1, cout1);
add16 instance2 = (a[31:16], x[31:16], cout1, sum2, cout2);
assign sum = {sum2, sum1};
endmodule
//모듈 인스턴스화를 할 때 = 연산자를 사용하면 안된다.