How to take the absolute value of std_logic_vector? in vhdl

I cannot figure out how to take the absolute value of two std_logic_vector (31 to 0);

here is a sample code:

library ieee;
use ieee.std_logic_1164.all;        
use ieee.numeric_std.all;       -- for the signed, unsigned types and arithmetic ops
use ieee.std_logic_arith.all;
use ieee.std_logic_unsigned.all;
...
...
port (  
    X: in std_logic_vector(31 downto 0); 
    Y: in std_logic_vector(31 downto 0); 
    F: out std_logic_vector(31 downto 0) 
  );

..
..
..
process(X,Y)
 begin
 F <= abs(X-Y)     --this doesnt work
+3
source share
1 answer

Disable the non-standard library and use the standard type signed, which has a built-in function abs:

library ieee;
use ieee.std_logic_1164.all;        
use ieee.numeric_std.all; -- this is the standard package where signed is defined
-- never use non-standard ieee.std_logic_arith and ieee.std_logic_unsigned

...

port (  
  X: in  std_logic_vector(31 downto 0); 
  Y: in  std_logic_vector(31 downto 0); 
  F: out std_logic_vector(31 downto 0) 
);

...

process(X,Y) is
begin
  F <= std_logic_vector(abs(signed(X)-signed(Y)));
end process;

There are many [possibly unnecessary] conversions between std_logic_vectorand on the last line signed, so you might prefer this interface if it makes sense with the rest of your design:

port (  
  X: in  signed(31 downto 0); 
  Y: in  signed(31 downto 0); 
  F: out signed(31 downto 0) 
);

Then the last line is simple:

 F <= abs(X-Y);
+6
source

All Articles