1. 程式人生 > 其它 >HDLBits->Circuits->Multiplexers->Mux256to1v

HDLBits->Circuits->Multiplexers->Mux256to1v

Verilog切片語法

題目要求如下

Create a 4-bit wide, 256-to-1 multiplexer. The 256 4-bit inputs are all packed into a single 1024-bit input vector. sel=0 should select bits in[3:0], sel=1 selects bits in[7:4], sel=2 selects bits in[11:8], etc.

提供的頂層模組如下

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

初次編寫的程式碼如下

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

此時程式碼執行會產生報錯

Error (10734): Verilog HDL error at top_module.v(5): sel is not a constant File: /home/h/work/hdlbits.4558136/top_module.v Line: 5

這條報錯我百思不得其解,然後看到題目給出的提示資訊

.With this many options, a case statement isn't so useful.
.Vector indices can be variable, as long as the synthesizer can figure out that the width of the bits being selected is constant. It's not always good at this. An error saying "... is not a constant" means it couldn't prove that the select width is constant. In particular, in[ sel*4+3 : sel*4 ] does not work.
.Bit slicing ("Indexed vector part select", since Verilog-2001) has an even more compact syntax.

這條提示的意思就是說警告中的not a constant File意味著它不能夠證明選擇的寬度是一個常數,Verilog不支援這種語法,然後注意到最後一段說的Bit slicing(位切片)方法。通過網上查詢,發現相關語法如下

[M -: N]  // negative offset from bit index M, N bit result 
[M +: N]  // positive offset from bit index M, N bit result

其中M是指的起始的我們的索引的位置,加減號是指的從索引位置位置向上還是向下切片,而N是指的我們切片的長度。
通過以下的小例子就可以解釋這個語法

bit [7:0] PA, PB;
int loc;

initial begin
  loc = 3;
  PA = PB;                      // Read/Write
  PA[7:4] = 'hA;                // Read/Write of a slice
  PA[loc -:4] = PA[loc+1 +:4];  // Read/Write of a variable slice equivalent to PA[3:0] = PA[7:4];
end

所以我們將程式碼做如下修改

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

然後答案就正確了。