VHDL highest possible integer

Status
Not open for further replies.
Code:
	function log2_unsigned ( x : natural ) return natural is
		variable temp : natural := x ;
		variable n : natural := 1 ;
	begin
		while temp > 1 loop
			temp := temp / 2 ;
			n := n + 1 ;
		end loop ;
		return n ;
	end function log2_unsigned ;

Will simply changing "natural" with "string" work ?
 

Will simply changing "natural" with "string" work ?

No, but here is a working version:


Code VHDL - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
 
function decimal_string_bits_needed(decimal_string: string) return natural is
constant maximum_bitwidth: positive := 512;
variable tmp_unsigned: unsigned(maximum_bitwidth+3 downto 0) := (others => '0'); -- 4 extra bits to detect overflow
variable character_value: integer;
begin
  for string_pos in decimal_string'range loop
    case decimal_string(string_pos) is
      when '0' => character_value := 0;
      when '1' => character_value := 1;
      when '2' => character_value := 2;
      when '3' => character_value := 3;
      when '4' => character_value := 4;
      when '5' => character_value := 5;
      when '6' => character_value := 6;
      when '7' => character_value := 7;
      when '8' => character_value := 8;
      when '9' => character_value := 9;
      when others => report("Illegal number") severity failure;
    end case;
    tmp_unsigned := tmp_unsigned(maximum_bitwidth-1 downto 0) * to_unsigned(10, 4);
    tmp_unsigned := tmp_unsigned + character_value;
    if tmp_unsigned(maximum_bitwidth+3 downto maximum_bitwidth) /= "0000" then
      report("Too large number") severity failure;
    end if;
  end loop;
  
  for i in tmp_unsigned'range loop
    if tmp_unsigned(i) = '1' then
      return i+1;
    end if;
  end loop;
  return 1;
end decimal_string_bits_needed;



As discussed in another thread, I don't want to call it "log2" since it is really ceil(log2(n+1)) and the special input argument zero returns '1'.

The method to detect too large numbers can be applied also to the function "decimal_string_to_unsigned".
 
Last edited:
Reactions: shaiko

    shaiko

    Points: 2
    Helpful Answer Positive Rating
Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…