Verilog自编函数clog2替代SV中的系统函数$clog2
生活随笔
收集整理的這篇文章主要介紹了
Verilog自编函数clog2替代SV中的系统函数$clog2
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
先放函數,已驗證和$clog2輸出一致,注意需滿足輸入n ≥ 1。
// 返回以2為底的n的對數 function integer clog2 (input integer n); beginn = n - 1;for (clog2 = 0; n > 0; clog2 = clog2 + 1)n = n >> 1; end endfunction另外,經評論區提醒,在Vivado 2017以后的版本中,可以直接使用系統函數$clog2(),不需要去自編函數了。后續又測試了Quartus 18.1 同樣支持$clog2(),各位可自行測試使用的工具是否支持$clog2()。
一.為什么需要以2為底n的對數的函數
在Verilog編寫代碼過程中,經常需要根據一個常量來定義一個變量的位寬,例如,要編寫一個計數器,計數最大值為常量N,那么計數變量cnt的位寬應該是多少呢?這個問題在SV可利用系統函數$clog2來解決,如下:
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中沒有這個系統函數,所以需要自行編寫。
二.Verilog編寫求以2為底n的對數的函數
將上面計數器的SV代碼改為Verilog,用自編的clog2替代SV的系統函數$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為底的對數函數 function integer clog2 (input integer n); beginn = n - 1;for (clog2 = 0; n > 0; clog2 = clog2 + 1)n = n >> 1; end endfunctionendmodule三.仿真驗證
仿真驗證自編函數clog2的輸出和SV系統函數$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為底的對數函數 function integer clog2 (input integer n); beginn = n - 1;for (clog2 = 0; n > 0; clog2 = clog2 + 1)n = n >> 1; end endfunctionendmodule部分仿真結果:
可見,clog2(n) 與 $clog2(n) 輸出一致。
總結
以上是生活随笔為你收集整理的Verilog自编函数clog2替代SV中的系统函数$clog2的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Anaconda简介及其下载 安装 配置
- 下一篇: Python IDLE 如何清屏