standard function for calculating the number of bits of a natural number?

F

Frank Buss

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.
 
D

David Bishop

Frank said:
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;
 
F

Frank Buss

David said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top