[心得] 用Verilog/SystemVerilog計算log2
寫HDL以來一直有個困擾,就是log2計算很常見,
例如8-to-1多工器的選擇訊號是log2(8) = 3,
如果不能計算log2,很多電路就很難寫得一般化。
Verilog是有定義log2的function,叫作$clog2,
Design Compiler有支援,但Xilinx XST 12.1與
Mentor Graphics Precision RTL 2009都不支援 XD
今天去google了一下,找到答案[1],雖然[1]有些小bug。
我用SystemVerilog稍微改寫,
讓大家欣賞寫function的powerful,如下:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function automatic integer log2;
input integer in;
integer in2;
begin
in2 = in;
for(log2 = 0; in2 > 1; log2 = log2+1) begin
in2 = in2>>1;
end
end
endfunction
module Mux(o, i, sel);
parameter Len = 8;
output o;
input [Len-1:0] i;
input [log2(Len)-1:0] sel;
assign o = i[sel];
endmodule
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
我以前很少寫function,沒想到function有這麼powerful的地方。
另外我用SystemVerilog改寫的原因是因為Verilog不支援
"global" function(我不知有無標準稱呼)。
以上code已用Precision RTL 2009、Design Compiler 2009.06合成過。
(XST 12.1還是沒支援SystemVerilog XD)
[1] http://objectmix.com/verilog/189123-how-do-log2-n-verilog.html
--
信佛的人要知道:佛絕不會說謊。但請把握時光。
法滅盡經:
http://www.cbeta.org/result/normal/T12/0396_001.htm
共勉之。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.115.221.79
→
06/18 09:57, , 1F
06/18 09:57, 1F
討論串 (同標題文章)