HDLBits 刷题——verilog language Module--Adder-subtractor
题目内容
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] XOR with sub replicated 32 times. See replication operator.) Also connect the sub input to the carry-in of the adder.
Module Declaration 模块说明
module top_module(
input [31:0] a,
input [31:0] b,
input sub,
output [31:0] sum
);
Solution
module top_module(
input [31:0] a,
input [31:0] b,
input sub,
output [31:0] sum
);
wire w1;
wire [31:0] w2;
parameter N = 32;
//方法一
/*
always @(*) begin
for (integer i = 0; i < N; i = i + 1)
w2[i] = (b[i]^sub);
end
*/
//方法二、方法三
/*
genvar i;
generate
for (i = 0; i < N; i = i + 1)
begin: myloop
//连续赋值语句
// assign w2[i] = (b[i]^sub);
//门级原语
xor gl (w2[i], b[i], sub);
end
endgenerate
*/
//方法四
//This can also be viewed as b[31:0] XOR with sub replicated 32 times.
assign w2 = (b^{32{sub}});
add16 ins0( .a(a[15:0]), .b(w2[15:0]), .cin(sub), .sum(sum[15:0]), .cout(w1) );
add16 ins1( .a(a[31:16]), .b(w2[31:16]), .cin(w1), .sum(sum[31:16]));
endmodule