下面使system verilog手册的原文描述
The system function $clog2 shall return the ceiling of the log base 2 of the argument (the log rounded up to
an integer value). The argument can be an integer or an arbitrary sized vector value. The argument shall be
treated as an unsigned value, and an argument value of 0 shall produce a result of 0.
This system function can be used to compute the minimum address width necessary to address a memory of
a given size or the minimum vector width necessary to represent a given number of states.
For example:
integer result;
result = $clog2(n);
- $clog2(n)的参数n必须为整数,否则会报错,所以我们用的时候如果n是浮点型的,需要使用int’(n)转换一下,然后转换的规则是四舍五入
- n=0时,得到的结果是0,这个算是强制规定,因为log2(x) 的定义域x>0,正常是取不到0的
- n=1时,得到的结果是0,这个是合理的
- n=2时,得到的结果是1
- n=3~4时,得到的结果是2
- n=5~8时,得到的结果是3
- …以此类推,由于此函数是向上取整,所以如果有n个数我们使用$clog2(n)的位宽变量正好能够放下,即 [ $clog2(n)-1 : 0]
顺带$ceil(x)是向上取整,x可以是浮点型, $ceil(1.1)=2.0, $ceil(1.8)=2.0
我们也可以像下面这样联合使用这三个函数,在一些计算中比较有用,比如我们需要使用两个寄存器来表示数N,
这两个寄存器位宽都是3,N={reg2,reg1},我们知道N的值可以通过下面来计算reg2和reg1的值
当N<7时 reg2=0,reg1=N
当N>=63时 reg2=7, reg1=7
当7=<N<63 reg2=$clog2(int’($ceil(1.0*N/7))) reg1=N%7 (这里面重要的是,当7<N<14时候我们需要让reg2=1, 另外前面需要加1.0要不10/7直接等于1,前面的ceil函数起不了作用)
$clog2(int’($ceil(1.2)))=1
$clog2(int’(1.2))=0