题解 | 位拆分与运算

位拆分与运算

https://www.nowcoder.com/practice/1649582a755a4fabb9763d07e62a9752

`timescale 1ns/1ns
module data_cal(
    input clk,
    input rst,
    input [15:0] d,
    input [1:0] sel,
    output reg [4:0] out,//除了四位还需预留一位给进位
    output reg validout
);

reg [15:0] d_lock;

always@(posedge clk or negedge rst)begin
    if(!rst)begin
        d_lock <= 16'b0;
    end
    else if(sel == 2'b00)begin
        d_lock <= d;//当sel为0时输入有效
    end
end

always@(posedge clk or negedge rst)begin
    if(!rst)begin
        out <= 5'b0;
        validout <= 1'b0;
    end
    else begin
        case(sel)
        2'b00:begin
            out <= 5'b0;
            validout <= 1'b0;
        end
        2'b01:begin
            out <= d_lock[3:0] + d_lock[7:4];
            validout <= 1'b1;
        end
        2'b10:begin
            out <= d_lock[3:0] + d_lock[11:8];
            validout <= 1'b1;
        end
        2'b11:begin
            out <= d_lock[3:0] + d_lock[15:12];
            validout <= 1'b1;
        end
        default:begin
            out <= 15'b0;
            validout <= 1'b0;
        end
        endcase
    end
end

endmodule

verilog刷题记录 文章被收录于专栏

记录自己最近刷题掌握的点滴

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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