题解 | 流水线乘法器

流水线乘法器

https://www.nowcoder.com/practice/be97f63817c543fe9260d46d971a7283

`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   
);
  
/************************我的回答********************************************/
//用组合逻辑出结果比较快
//我把相加放到了组合逻辑里,答案比参考答案早了一个周期,直接给我判错了
// wire [size*2-1:0]  mul_temp0,mul_temp1,mul_temp2,mul_temp3,mul_a1; 

// assign mul_a1 = {{size{1'b0}},mul_a};
// assign mul_temp0 = mul_b[0] ? mul_a1 : 0;
// assign mul_temp1 = mul_temp0 +(mul_b[1] ? (mul_a1 << 1) : 0 );
// assign mul_temp2 = mul_temp1 +(mul_b[2] ? (mul_a1 << 2) : 0 );
// assign mul_temp3 = mul_temp2 +(mul_b[3] ? (mul_a1 << 3) : 0 );

// always@(posedge clk or negedge rst_n)
// if(!rst_n) 
// 	mul_out <= 0;
// else 
// 	mul_out <= mul_temp3;

/*****************参考答案***************************************************/
reg [7:0]  addr01;
reg [7:0]  addr23;
 
wire [7:0] temp0 ;
wire [7:0] temp1 ;
wire [7:0] temp2 ;
wire [7:0] temp3 ;
 
assign temp0 = mul_b[0]? {4'b0, mul_a} : 'd0;
assign temp1 = mul_b[1]? {3'b0, mul_a, 1'b0} : 'd0;
assign temp2 = mul_b[2]? {2'b0, mul_a, 2'b0} : 'd0;
assign temp3 = mul_b[3]? {1'b0, mul_a, 3'b0} : 'd0;
 
always @(posedge clk or negedge rst_n) begin 
    if(~rst_n) begin
        addr01  <= 'd0;
        addr23  <= 'd0;
        mul_out <= 'd0;
    end 
    else begin
        addr01 <= temp0 + temp1;
        addr23 <= temp2 + temp3;
 
        mul_out <= addr01 + addr23;
    end
end
endmodule
`timescale 1ns/1ns

module testbench;

    reg clk;
    reg rst_n;
    reg [3:0] mul_a;
    reg [3:0] mul_b;
    wire [7:0] mul_out;

    // 实例化待测模块(这里假设待测模块名为multi_pipe)
    multi_pipe #(
      .size(4)
    ) dut (
      .clk(clk),
      .rst_n(rst_n),
      .mul_a(mul_a),
      .mul_b(mul_b),
      .mul_out(mul_out)
    );

    // 时钟信号生成
    always #1 clk = ~clk;

    initial begin
        $dumpfile("out.vcd");
        // 将$dumpvars的第二个参数改为实例名dut
        $dumpvars(0, dut); 
        // 初始化信号
        clk = 0;
        rst_n = 0;
        mul_a = 0;
        mul_b = 0;

        // 释放复位
        #2;
        rst_n = 1;

        // 测试用例1
        mul_a = 4'd3;
        mul_b = 4'd4;
        #1;

        // 测试用例2
        mul_a = 4'd5;
        mul_b = 4'd6;
        #4;

        // 测试用例3
        mul_a = 4'd7;
        mul_b = 4'd8;
        #5;

        // 结束仿真
        #4;
        $finish;
    end
endmodule

这个是参考答案的代码自测跑出来的结果,当然是因为我设置的时间比较极限,所以算出来的结果不对。

我的答案自测跑出来的结果

全部评论

相关推荐

10-29 18:20
济南大学 Java
点赞 评论 收藏
分享
09-28 22:01
已编辑
广西科技大学 IT技术支持
合适才能收到offe...:找桌面运维?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务