对于数据取反,通常需要加入use ieee.std_logic_signed.all程序包。这里举例,对8位宽的数据进行取反操作。
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use ieee.std_logic_arith.all;
use ieee.std_logic_signed.all;
entity top is
port(
clk : in std_logic;
rst : in std_logic;
din : in std_logic_vector(7 downto 0);
dout : out std_logic_vector(7 downto 0)
);
end top;
architecture Behavioral of top is
begin
process(clk,rst)
begin
if rst = '1' then
dout <= (others => '0');
elsif rising_edge(clk) then
dout <= -din;
end if;
end process;
end Behavioral;
添加testbench,对代码仿真。
module tst_top;
// Inputs
reg clk;
reg rst;
reg [7:0] din;
// Outputs
wire [7:0] dout;
// Instantiate the Unit Under Test (UUT)
top uut (
.clk(clk),
.rst(rst),
.din(din),
.dout(dout)
);
initial begin
// Initialize Inputs
clk = 0;
rst = 1;
din = 8'd0;
// Wait 100 ns for global reset to finish
#100;
rst = 0;
end
always @(posedge clk)
begin
din <= din + 1;
end
always #5 clk =~clk;
endmodule
设计对渐加数取反,在Modelsim上观察仿真结果
现象:根据仿真结果看,在输入10000000(-128)时,输出为10000000(-128),结果出错。
分析出错原因:8位有符号数的表示范围为-128~127,无法表示128,所以溢出导致出错。
解决方法:判断输入数据是否为10000000。是,输出127;否,直接取反。