standard function for calculating the number of bits of a na

F

Frank Buss

Guest
I'm using this function for calculating the number of bits needed to encode
a natural number:

function num_bits(n: natural) return natural is
begin
if n > 0 then
return 1 + num_bits(n / 2);
else
return 1;
end if;
end num_bits;

I wonder if there is already such a function in the IEEE.* libraries or
some special VHDL operator.

--
Frank Buss, fb@frank-buss.de
http://www.frank-buss.de, http://www.it4-systems.de
 
Frank Buss wrote:
I'm using this function for calculating the number of bits needed to encode
a natural number:

function num_bits(n: natural) return natural is
begin
if n > 0 then
return 1 + num_bits(n / 2);
else
return 1;
end if;
end num_bits;

I wonder if there is already such a function in the IEEE.* libraries or
some special VHDL operator.
Try this one:

function log2 (A : NATURAL) return NATURAL is
begin
for I in 1 to 30 loop -- Works for up to 32 bits
if (2**I > A) then return(I-1);
end if;
end loop;
return(30);
end function log2;
 
David Bishop wrote:

Try this one:

function log2 (A : NATURAL) return NATURAL is
begin
for I in 1 to 30 loop -- Works for up to 32 bits
if (2**I > A) then return(I-1);
end if;
end loop;
return(30);
end function log2;
This is just another self-written function, which could be written with a
"while" loop for >32 bits. But I've found a solution:

use IEEE.MATH_REAL.ALL;

integer(trunc(log2(real(value)))) + 1

But this could cause problems, depending on the mantissa size of floating
point numbers in the VHDL implementation and when "value" is near 2**n
(with n=1,2,3...), e.g. if 2**32=4294967296 is represented as 4.294e9,
because then the result is 32, but you'll need 33 bits for storing the
number 2**32. Would be nice to have a log2 and looks like something like
this is defined in some Xilinx VHDL library files, but not in a standard
VHDL IEEE library.

Looks like I have to create my own package with such utility functions.

--
Frank Buss, fb@frank-buss.de
http://www.frank-buss.de, http://www.it4-systems.de
 
Frank Buss wrote:

Looks like I have to create my own package with such utility functions.
I have collected some of my vector length functions here:

http://home.comcast.net/~mike_treseler/min_vec_len.vhd

-- Mike Treseler
 

Welcome to EDABoard.com

Sponsor

Back
Top