Verilog——vect[a +: b]或vect [a -: b]

这是一种常见的数据选择语句

vect[a +: b]vect [a -: b]
a表示起始位,b表示数据位宽,+,-表示升序或者降序。
例如vect[2 +: 5]表示起始位是2,升序,数据位宽位5,那么从2往上数5个就是:2,3,4,5,6;所以这个表达式也就是代表了vect[2:6]
同理vect[3 -: 4]就表示vect[3:0];

那么为什么不谢vect[3:0],而要写不容易读懂的形式呢?

这是因为再做数据选择的时候可能我们要面对的不仅仅是常数,还需要面对变量,当起始位的变量与结束位的变量之间的位宽固定的时候,我们就需要这种表达形式,似乎vect[i * 4 + 3 : i]这种语法是走不通的。

module top_module( 
    input [1023:0] in,
    input [7:0] sel,
    output [3:0] out );
    assign out = in[sel*4: sel];
endmodule

写成这种模式就会报错,似乎方括号中冒号两端不能同事出现变量!!!

module top_module (
	input [1023:0] in,
	input [7:0] sel,
	output [3:0] out
);

	// We can't part-select multiple bits without an error, but we can select one bit at a time,
	// four times, then concatenate them together.
	assign out = {in[sel*4+3], in[sel*4+2], in[sel*4+1], in[sel*4+0]};

	// Alternatively, "indexed vector part select" works better, but has an unfamiliar syntax:
	// assign out = in[sel*4 +: 4];		// Select starting at index "sel*4", then select a total width of 4 bits with increasing (+:) index number.
	// assign out = in[sel*4+3 -: 4];	// Select starting at index "sel*4+3", then select a total width of 4 bits with decreasing (-:) index number.
	// Note: The width (4 in this case) must be constant.

endmodule

这是正确的代码

posted @ 2022-08-14 15:44  xing-uestc  阅读(823)  评论(0)    收藏  举报