题解 | 移位运算与乘法

`timescale 1ns/1ns
module multi_sel(
input [7:0]d ,
input clk,
input rst,
output reg input_grant,
output reg [10:0]out
);
//*************code***********//
reg [1:0] cnt;
reg [10:0] d_reg;

always@(posedge clk or negedge rst)
    if (~rst) begin
        cnt <= 2'd0;
    end else begin
        cnt <= cnt + 1'b1;
    end


always@(posedge clk or negedge rst)
    if (~rst) begin
        d_reg <= 8'd0;
    end else if (cnt == 2'd0) begin
        d_reg <= d;
    end

always@(posedge clk or negedge rst)
    if (~rst) begin
        out <= 11'd0;
        input_grant <= 1'b0;
    end else begin
        case (cnt)
            2'b00:begin out <= d; input_grant <= 1'b1; end
            2'b01:begin out <= (d_reg<<2) - d_reg; input_grant <= 1'b0; end
            2'b10:begin out <= (d_reg<<3) - d_reg; input_grant <= 1'b0; end
            2'b11:begin out <= (d_reg<<3); input_grant <= 1'b0; end
            default : begin out <= 11'd0; input_grant <= 1'b0; end
        endcase
    end


//*************code***********//
endmodule

上下两种方式,在out取值上是不一致的:思考时序逻辑和组合逻辑的差异~

`timescale 1ns/1ns
module multi_sel(
    input [7:0]d ,
    input clk,
    input rst,
    output reg input_grant,
    output reg [10:0]out
);

    // 状态定义
    parameter IDLE = 0, MULT1 = 1, MULT2 = 2, MULT3 = 3, MULT4 = 4 ;

    reg [2:0] state,next;
    reg [7:0] d_reg;
    // 状态更新逻辑
    always @(posedge clk or negedge rst) begin
        if (~rst) begin
            state <= IDLE;
        end else begin
            state <= next;
        end
    end

    always @(posedge clk or negedge rst) begin
        if (~rst) begin
            d_reg <= 0;
        end else if (next==MULT1) begin
            d_reg <= d;
        end
    end
    // 状态转移逻辑
    always @(*) begin
        case (state)
            IDLE : begin next = MULT1;input_grant = 1'b0; out = 0;                    ;end
            MULT1: begin next = MULT2;input_grant = 1'b1; out = d_reg;                ;end
            MULT2: begin next = MULT3;input_grant = 1'b0; out = (d_reg << 1) + d_reg  ;end  //3d
            MULT3: begin next = MULT4;input_grant = 1'b0; out = (d_reg << 3) - d_reg  ;end  //7d
            MULT4: begin next = MULT1 ;input_grant = 1'b0; out = (d_reg << 3)         ;end  //8d
            default: begin
                state = IDLE;
                input_grant = 1'b0;
                out = 0  ;
            end
        endcase
    end



endmodule

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务