Electronic – VHDL logical operation on integer

vhdl

I have some VHDL code that has the following signal definition:

signal hcount  : integer range 0 to 235;

This is used as a counter throughout my system (so I believe it needs to continue as an integer and not be declared as a std_logic_vector for example), but I also need to use its least 3 significant bits to index an eight-bit signal like this (which does not compile):

signal somereg : std_logic_vector(7 downto 0);
...
somereg(hcount and B"00000111") <= <a bit value>;

What is the most appropriate way to index the "somereg" vector above?

Thanks

Best Answer

A better way than using std_logic_vector and the non-standard std_logic_arith and std_logic_signed libraries is to use IEEE.numeric_std.all; and make the counter unsigned (or signed in other contexts where you need negative values).

signal hcount  : unsigned(7 downto 0);

And you can perform conversions to and from integer, and bitwise operations:

hcount <= to_unsigned(123,hcount'length);

signal somereg : std_logic_vector(7 downto 0);
...
somereg(to_integer(hcount(2 downto 0)) <= <a bit value>;

However in the given example, the bitwise operations turn out to be unnecessary: instead of masking bits to extract a 3-bit register address, you could use division and mod operations. Synthesis tools (mostly) aren't stupid : divide and mod by powers of 2 are optimised into the obvious field extractions and don't even generate "and" gates.

signal hcount    : natural range 0 to 235;
signal reg_addr  : natural range 0 to 7;

signal somereg : std_logic_vector(7 downto 0);
...
reg_addr <= hcount mod 8;
somereg(reg_addr) <= <a bit value>;

One benefit of this (apart from fewer ugly type conversions) is that you still profit from the integer subtype you declared for hcount : incrementing it to 236 will raise an overflow error in simulation, allowing you to catch and correct logic errors early.

Related Topic