0
我正在嘗試用VHDL編寫兩個平均兩個和四個8位std_logic_vector輸入信號的包函數。當我實現下面的avgtwo代碼時,在我的模擬中得到的答案比預期的大2倍。這就像返回操作'sum(sum'high downto 1)'沒有取得高8位的總和......我錯過了什麼?函數計算std_logic_vector變量的平均值
library IEEE;
use IEEE.STD_LOGIC_1164.all;
use IEEE.STD_LOGIC_UNSIGNED.all;
use IEEE.NUMERIC_STD.ALL;
package my_package is
function avgtwo(v1, v2 : std_logic_vector) return std_logic_vector;
function avgfour(v1, v2, v3, v4 : std_logic_vector) return std_logic_vector;
end my_package;
package body my_package is
function avgtwo
(
v1, v2 : std_logic_vector
)
return std_logic_vector is
variable sum : std_logic_vector(v1'high+1 downto 0) := (others => '0');
begin
sum := std_logic_vector(unsigned(v1)) + std_logic_vector(unsigned(v2));
return sum(sum'high downto 1);
end function avgtwo;
function avgfour
(
v1, v2, v3, v4 : std_logic_vector
)
return std_logic_vector is
variable sum : std_logic_vector(v1'high+2 downto 0) := (others => '0');
begin
sum := std_logic_vector(unsigned(v1)) + std_logic_vector(unsigned(v2)) + std_logic_vector(unsigned(v3)) + std_logic_vector(unsigned(v4));
return sum(sum'high downto 2);
end function avgfour;
end my_package;