I am implementing a configurable DPRAM where RAM DEPTH is the parameter.
How to determine ADDRESS WIDTH from RAM DEPTH?
I know the relation RAM DEPTH = 2 ^ (ADDRESS WIDTH)
i.e ADDRESS WIDTH = log (base 2) RAM DEPTH.
How to implement the log (base 2) function in Verilog?
The
$clog2
system task was added to the SystemVerilog extension to Verilog (IEEE Std 1800-2005). This returns an integer which has the value of the ceiling of the log base 2. The DEPTH need not be a power of 2.Running a simulation will display this:
However, I do not know of a synthesis tool which supports
$clog2
. If you need to synthesize your code, you can use afunction
. This was copied from the IEEE 1364-2001 Std, but there are other versions floating around the web:My experience has been that using the
function
is more trouble than it's worth for synthesizable code. It has caused problems for other tools in the design flow (linters, equivalence checkers, etc.).While $clog2 is the correct answer, until the tool vendors catch up, you can implement your own clog2 function as a verilog-2001 macro, which will work with all synthesis and simulation tools.
Such as:
Where the final "-1" is used to produce an illegal value the the simulator should flag.
(late edit: oops, fixed my off-by-one error!)