题解 | #位拆分与运算#
位拆分与运算
https://www.nowcoder.com/practice/1649582a755a4fabb9763d07e62a9752
需要提前创建个锁存保留输入的d。
`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); /* * 现在输入了一个压缩的16位数据,其实际上包含了四个数据[3:0][7:4][11:8][15:12], * 现在请按照sel选择输出四个数据的相加结果,并输出valid_out信号(在不输出时候拉低) * 0: 不输出且只有此时的输入有效 * 1:输出[3:0]+[7:4] * 2:输出[3:0]+[11:8] * 3:输出[3:0]+[15:12] */ reg [15:0] record; always @(posedge clk or negedge rst) begin if (!rst) begin out <= 0; validout <= 0; record <= 0; end else begin case (sel) 0: begin out <= 0; validout <= 0; record <= d; end 1: begin out <= record[3:0] + record[7:4]; validout <= 1; end 2: begin out <= record[3:0] + record[11:8]; validout <= 1; end 3: begin out <= record[3:0] + record[15:12]; validout <= 1; end endcase end end endmodule