题解 | #位拆分与运算#
位拆分与运算
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 validout
);
//*************code***********//
reg [15:0] d_tmp;
wire [4:0] d1;
wire [4:0] d2;
wire [4:0] d3;
always @(posedge clk or negedge rst)
if(!rst)
d_tmp <= 16'b0;
else if(sel == 2'b00)
d_tmp <= d;
else d_tmp <= d_tmp;
assign d1 = d_tmp[3:0] + d_tmp[7:4];
assign d2 = d_tmp[3:0] + d_tmp[11:8];
assign d3 = d_tmp[3:0] + d_tmp[15:12];
assign validout = !(sel == 2'b00);
// assign out = (sel == 2'b00) ? 5'b0 : ((sel == 2'b01) ? d1 : ((sel == 2'b10) ? d2 : d3));
always @(*)
case(sel)
2'b00: out = 5'b0;
2'b01: out = d1;
2'b10: out = d2;
2'b11: out = d3;
endcase
//*************code***********//
endmodule
module data_cal(
input clk,
input rst,
input [15:0]d,
input [1:0]sel,
output reg [4:0]out,
output validout
);
//*************code***********//
reg [15:0] d_tmp;
wire [4:0] d1;
wire [4:0] d2;
wire [4:0] d3;
always @(posedge clk or negedge rst)
if(!rst)
d_tmp <= 16'b0;
else if(sel == 2'b00)
d_tmp <= d;
else d_tmp <= d_tmp;
assign d1 = d_tmp[3:0] + d_tmp[7:4];
assign d2 = d_tmp[3:0] + d_tmp[11:8];
assign d3 = d_tmp[3:0] + d_tmp[15:12];
assign validout = !(sel == 2'b00);
// assign out = (sel == 2'b00) ? 5'b0 : ((sel == 2'b01) ? d1 : ((sel == 2'b10) ? d2 : d3));
always @(*)
case(sel)
2'b00: out = 5'b0;
2'b01: out = d1;
2'b10: out = d2;
2'b11: out = d3;
endcase
//*************code***********//
endmodule