我想添加n位std_logic_vector的所有位。最简单的方法是什么? 例如:A< = 10011011。结果应该是101。 我可以在一个循环中调用一个波纹进位加法器。但有没有其他简单的方法来做到这一点?
答案 0 :(得分:0)
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
...
-- Loop-based
function hw_loop(v: std_logic_vector) return natural is
variable h: natural;
begin
h := 0;
for i in v'range loop
if v(i) = '1' then
h := h + 1;
end if;
end loop;
return h;
end function hw_loop;
...
-- Log-tree-based, using a recursive function:
function hw_tree(v: std_logic_vector) return natural is
constant size: natural := v'length;
constant vv: std_logic_vector(size - 1 downto 0) := v;
variable h: natural;
begin
h := 0;
if size = 1 and vv(0) = '1' then
h := 1;
elsif size > 1 then
h := hw_tree(vv(size - 1 downto size / 2)) + hw_tree(vv(size / 2 - 1 downto 0));
end if;
return h;
end function hw_tree;
...
signal A: std_logic_vector(7 downto 0);
signal B0, B1: std_logic_vector(2 downto 0);
...
B0 <= std_logic_vector(to_unsigned(hw_loop(A), 3));
B1 <= std_logic_vector(to_unsigned(hw_tree(A), 3));
...
注意:
std_ulogic
和std_ulogic_vector
代替std_logic
和std_logic_vector
。