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.
译:
可以通过选择性地否定加法器的一个输入来构建一个加法-减法器,这相当于先反转输入然后再加1。最终结果是一个能够执行两种操作的电路:(a + b + 0) 和 (a + ~b + 1)。如果您想要更详细的解释,可以查阅Wikipedia。
请构建下面的加法-减法器。
您将获得一个16位加法器模块,您需要实例化两次:
module add16 ( input[15:0] a, input[15:0] b, input cin, output[15:0] sum, output cout );
使用一个32位宽的异或门,在sub输入为1时反转b输入。(这也可以理解为将b[31:0]与复制了32次的sub进行异或操作。有关复制操作符的详细信息,请参阅相关资料。)同时,将sub输入连接到加法器的进位输入。
module top_module(
input [31:0] a,
input [31:0] b,
input sub,
output [31:0] sum
);
wire [15:0]sum1,sum2;
wire [31:0]sum_sub;
wire cout_1;
assign sum_sub = (sub == 1'b1) ? (~b + 32'b1) : b;
add16 add_1(a[15:0],sum_sub[15:0],1'b0,sum1[15:0],cout_1);
add16 add_2(a[31:16],sum_sub[31:16],cout_1,sum2[15:0]);
assign sum = {sum2,sum1};
endmodule
题目分析:
要求构建一个能够执行加法和减法操作的加法器-减法器电路。在修改后的代码中,我们首先根据 sub
的值来选择是否对输入 b
进行取反操作,然后将处理后的输入分别连接到两个实例化的 add16
模块中进行加法运算。
第一个 add16
模块执行低 16 位的加法操作,如果有进位则传递给下一个模块;第二个 add16
模块执行高 16 位的加法操作,并将来自第一个模块的进位作为输入。最终,我们将得到正确的结果并输出到 sum
中。
通过这样的设计,我们实现了一个能够根据 sub
输入执行加法或减法操作的电路。
问题点: 三元操作符 x ? y : z ;即 x是否为1(或真)若是返回y,若不是则返回z
运行结果: