4bit数相乘,则需要进行4次加法。乘数a和乘数b的最低位到最高位逐位相乘再相加。即如果b的第n位为0,则乘积为0,左移n位。如b的第n位为1,则乘积为a,左移n位。由此得到了乘法器的一种简单实现方法。
解题过程:
根据上述过程,求解两个数的乘积,语句如下:
module mult(
input clk ,
input rst_n ,
input [3:0] multiplicand,
input [3:0] multiplier ,
output reg [7:0] product
);
wire [7:0] temp0 ;
wire [7:0] temp1 ;
wire [7:0] temp2 ;
wire [7:0] temp3 ;
assign temp0 = multiplicand[0]? {4'b0, multiplier} : 1'd0;
assign temp1 = multiplicand[1]? {3'b0, multiplier, 1'b0} : 1'd0;
assign temp2 = multiplicand[2]? {2'b0, multiplier, 2'b0} : 1'd0;
assign temp3 = multiplicand[3]? {1'b0, multiplier, 3'b0} : 1'd0;
always @(posedge clk or negedge rst_n) begin
if(~rst_n) begin
product <= 1'd0;
end
else begin
product <= temp0 + temp1 + temp2 + temp3;
end
end
然后在主模块中,分别例化两次乘法器,将乘积相加即可得到算式的结果。将常量12,5声明为reg类,作为乘法器的一个乘数。
module calculation(
input clk,
input rst_n,
input [3:0] a,
input [3:0] b,
output [8:0] c
);
wire [7:0] product_1;
wire [7:0] product_2;
reg[3:0] mult_1 = 12;
reg[3:0] mult_2 = 5;
mult multiplier_1(
.clk(clk),
.rst_n(rst_n),
.multiplicand(a),
.multiplier(mult_1),
.product(product_1)
);
mult multiplier_2(
.clk(clk),
.rst_n(rst_n),
.multiplicand(b),
.multiplier(mult_2),
.product(product_2)
);
assign c = product_1+product_2;
endmodule
仿真结果:
`timescale 1ns/1ns module calculation( input clk, input rst_n, input [3:0] a, input [3:0] b, output [8:0] c ); wire [7:0] product_1; wire [7:0] product_2; reg[3:0] mult_1 = 12; reg[3:0] mult_2 = 5; mult multiplier_1( .clk(clk), .rst_n(rst_n), .multiplicand(a), .multiplier(mult_1), .product(product_1) ); mult multiplier_2( .clk(clk), .rst_n(rst_n), .multiplicand(b), .multiplier(mult_2), .product(product_2) ); assign c = product_1+product_2; endmodule module mult( input clk , input rst_n , input [3:0] multiplicand, input [3:0] multiplier , output reg [7:0] product ); wire [7:0] temp0 ; wire [7:0] temp1 ; wire [7:0] temp2 ; wire [7:0] temp3 ; assign temp0 = multiplicand[0]? {4'b0, multiplier} : 1'd0; assign temp1 = multiplicand[1]? {3'b0, multiplier, 1'b0} : 1'd0; assign temp2 = multiplicand[2]? {2'b0, multiplier, 2'b0} : 1'd0; assign temp3 = multiplicand[3]? {1'b0, multiplier, 3'b0} : 1'd0; always @(posedge clk or negedge rst_n) begin if(~rst_n) begin product <= 1'd0; end else begin product <= temp0 + temp1 + temp2 + temp3; end end endmodule
如果关于此次题单有问题或者反馈意见,欢迎加入牛客用户反馈群沟通~