Verilog自编函数clog2替代SV中的系统函数$clog2
先放函數(shù),已驗(yàn)證和$clog2輸出一致,注意需滿足輸入n ≥ 1。
// 返回以2為底的n的對(duì)數(shù) function integer clog2 (input integer n); beginn = n - 1;for (clog2 = 0; n > 0; clog2 = clog2 + 1)n = n >> 1; end endfunction另外,經(jīng)評(píng)論區(qū)提醒,在Vivado 2017以后的版本中,可以直接使用系統(tǒng)函數(shù)$clog2(),不需要去自編函數(shù)了。后續(xù)又測(cè)試了Quartus 18.1 同樣支持$clog2(),各位可自行測(cè)試使用的工具是否支持$clog2()。
一.為什么需要以2為底n的對(duì)數(shù)的函數(shù)
在Verilog編寫(xiě)代碼過(guò)程中,經(jīng)常需要根據(jù)一個(gè)常量來(lái)定義一個(gè)變量的位寬,例如,要編寫(xiě)一個(gè)計(jì)數(shù)器,計(jì)數(shù)最大值為常量N,那么計(jì)數(shù)變量cnt的位寬應(yīng)該是多少呢?這個(gè)問(wèn)題在SV可利用系統(tǒng)函數(shù)$clog2來(lái)解決,如下:
module counter #(parameter CNT_MAX = 1023 )(output logic cnt_finish,input logic clk,input logic rstn );logic [$clog2(CNT_MAX+1)-1 : 0] cnt; always_ff @(posedge clk, negedge rstn) beginif (~rstn)cnt <= '0;else if (cnt < CNT_MAX)cnt <= cnt + 1'b1;elsecnt <= '0; endassign cnt_finish = cnt == CNT_MAX;endmodule但是在Verilog中沒(méi)有這個(gè)系統(tǒng)函數(shù),所以需要自行編寫(xiě)。
二.Verilog編寫(xiě)求以2為底n的對(duì)數(shù)的函數(shù)
將上面計(jì)數(shù)器的SV代碼改為Verilog,用自編的clog2替代SV的系統(tǒng)函數(shù)$clog2
module counter #(parameter CNT_MAX = 1023 )(output wire cnt_finish,input wire clk,input wire rstn );reg [clog2(CNT_MAX+1)-1 : 0] cnt; always @(posedge clk, negedge rstn) beginif (~rstn)cnt <= 'd0;else if (cnt < CNT_MAX)cnt <= cnt + 1'b1;elsecnt <= 'd0; endassign cnt_finish = cnt == CNT_MAX;// 以2為底的對(duì)數(shù)函數(shù) function integer clog2 (input integer n); beginn = n - 1;for (clog2 = 0; n > 0; clog2 = clog2 + 1)n = n >> 1; end endfunctionendmodule三.仿真驗(yàn)證
仿真驗(yàn)證自編函數(shù)clog2的輸出和SV系統(tǒng)函數(shù)$clog2的輸出是否一致,仿真工具:modelsim SE-64 2020.4,testbench(try_tb.sv)如下:
module try_tb();timeunit 1ns; timeprecision 10ps;initial beginfor (integer i=1; i<1025; i++) begin$display("$clog(%d) = %d, clog2(%d) = %d", i, $clog2(i), i, clog2(i));end end// 以2為底的對(duì)數(shù)函數(shù) function integer clog2 (input integer n); beginn = n - 1;for (clog2 = 0; n > 0; clog2 = clog2 + 1)n = n >> 1; end endfunctionendmodule部分仿真結(jié)果:
可見(jiàn),clog2(n) 與 $clog2(n) 輸出一致。
總結(jié)
以上是生活随笔為你收集整理的Verilog自编函数clog2替代SV中的系统函数$clog2的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Anaconda简介及其下载 安装 配置
- 下一篇: 参考用-惯性导航系统简介(转载)