题解 | #流水线乘法器#
流水线乘法器
http://www.nowcoder.com/practice/be97f63817c543fe9260d46d971a7283
- 定义部分积寄存器part_mul,大小和mul_out相同;
reg [size*2-1:0] part_mul[size-1:0];
- 根据乘数mul_b的第 j 位是否为1来决定部分积的值,若为1,其值等于被乘数左移 j 位,若为0,该部分积置零,用左移8位实现;
part_mul[j] <= {4'd0, mul_a} << (mul_b[j]? j: 8);
完整代码:
`timescale 1ns/1ns
module multi_pipe#(
parameter size = 4
)(
input clk ,
input rst_n ,
input [size-1:0] mul_a ,
input [size-1:0] mul_b ,
output reg [size*2-1:0] mul_out
);
reg [size*2-1:0] part_mul[size-1:0];
integer j;
always@(posedge clk or negedge rst_n)begin
if(~rst_n)begin
mul_out <= 0;
for(j=0;j<size;j=j+1)
part_mul[j] = 0;
end
else begin
for(j=0;j<size;j=j+1)
part_mul[j] <= {4'd0, mul_a} << (mul_b[j]? j: 8);
mul_out <= part_mul[0]+part_mul[1]+part_mul[2]+part_mul[3];
end
end
endmodule