VL5 位拆分与运算
题目描述:
现在输入了一个压缩的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]

写法一:
`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***********//
assign validout = rst & (sel != 0);
reg [15:0] temp;
always @(*)
if(sel == 0) temp = d;
always @(*) begin
if(!rst) out <= 0;
else begin
case(sel)
2'b00: out = 0;
2'b01: out = temp[3:0]+ temp[7:4];
2'b10: out = temp[3:0]+ temp[11:8];
2'b11: out = temp[3:0]+ temp[15:12];
default:out = 0;
endcase
end
end
//*************code***********//
endmodule
写法二:
`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***********//
assign validout = rst & (sel != 0);
reg [15:0] temp;
always @(posedge clk , negedge rst) begin
if(!rst) temp <= 0;
else if(sel == 0) temp <= d;
end
always @(*) begin
case(sel)
2'b00: out = 0;
2'b01: out = temp[3:0]+ temp[7:4];
2'b10: out = temp[3:0]+ temp[11:8];
2'b11: out = temp[3:0]+ temp[15:12];
default:out = 0;
endcase
end
//*************code***********//
endmodule
比较:
写法一temp部分会产生latch
写法二更好
补充:
什么情况下会产生 latch?
只有在 组合逻辑过程块(always @(*)) 中,变量未在所有分支赋值时,才会推断 latch。
总结:
1.wire 用 assign,reg 用 always
2.要存储,用时钟
3.从输出波形看,sel 和 out 同步变化,所以可以用组合逻辑。
关于采样
always @(posedge clk , negedge rst) begin
if(!rst) temp <= 0;
else if(sel == 0) temp <= d;
end
在时钟上升沿时,如果sel == 0,则d会给temp,
也就是说,d是和sel同周期的那个d。
这样也符合要求:sel=0: 不输出且只有此时的输入有效 。
另外,
假设rst 固定为1 , sel 固定为 0 ,那么temp的变化比d晚一拍。
注意:这种写法不对,因为组合逻辑块不能用 <= 非阻塞赋值。
always @(*) begin
if(!rst) temp <= 0;
else if(sel == 0) temp <= d;
end
266

被折叠的 条评论
为什么被折叠?



