0

Can anyone tel me how to calculate the log value of a parameter in a design file?

I am coming across such a situation where I have a generate for a loop like this:

parameter N=8;

genvar i,m;

generate
for(m=1;m<N;m=m*2)
begin :m_loop

    // I have an instance here
    // "in" is an input of N bits, "out" is an output N bits

    Inst u(in(i+log2(m)),in(i+1+log2(m)),out(i+log2(m)));     
end
endgenerate

Is there a way to do log2(m), where m varies as powers of 2 (2^0,2^1,2^2, till N)? If not,

I was thinking of introducing a new variable, m1, say, which is 0,1,2,... (i.e log2(m)).

In such a case m1 should vary with simultaneously every m, ie, when m=1,m1=0; m=2,m1=1;

m=4,m1=2; m=8,m1=3 and so on.

Greg
  • 16,013
  • 5
  • 43
  • 61
Nandhini
  • 49
  • 2
  • 2
  • 7

2 Answers2

1

Given this is obviously not intended to be synthesised, and that N is only 8, could you just generate (with a pair of nested for loops) an array of 2^N values, each containing the inverse log - then you could just index into that with 'm' to get the answer.

You could even generate the source for a table using a less awful language than Verilog, and just load it it.

Update:

ADDRESS WIDTH from RAM DEPTH might be relevant too, if you're only interested in answers for exact powers of two.

Community
  • 1
  • 1
Will Dean
  • 37,648
  • 10
  • 84
  • 116
  • Thank you Will, but iam parameterizing a KS Adder. For just an example I have kept N as 8 here. It can take any value since it is going to be just a simulation. – Nandhini Apr 22 '11 at 08:20
  • @ Will, Thank you, i think this will be the only way out and I am thinking of doing it only till N=256. – Nandhini Apr 25 '11 at 06:48
0

What you want is the ceiling of the log base 2.

If your simulator supports IEEE 1364-2005 or any IEEE 1800 then use $clog2. Ex.:

Inst u(in[i+$clog2(m)], in[i+1+$clog2(m)], out[i+$clog2(m)]);  

If your limited to IEEE 1364-2001, then use a 'pure function' with a know parameter as the input to assign another parameter. A 'pure function' is defined as a function who's output only calculated by its inputs. The following is a snip-it based on the example in IEEE 1800-2012 section 13.4.3. It is the same example is used in all Verilog (& SystemVerilog) versions since 1364-2001. 1800-2012 is the is the only version you can download for free from IEEE.

parameter ram_depth = 256;
parameter addr_width=clogb2(ram_depth); // width is 8
/* ... */
function integer clogb2(input [31:0] value);
  value = value -1;
  for(clogb2=0; value>0; clogb2=clogb2+1)
    value = value >> 1;
endfunction

The same clogb2() function should work with genvar types.

Greg
  • 16,013
  • 5
  • 43
  • 61