What to_unsigned does?

Sasa Stamenkovic picture Sasa Stamenkovic · Oct 21, 2015 · Viewed 36.1k times · Source

Could someone please explain me how VHDL's to_unsigned works or confirm that my understanding is correct? For example:

C(30 DOWNTO 0) <= std_logic_vector (to_unsigned(-30, 31))

Here is my understanding:

  • -30 is a signed value, represented in bits as 1111111111100010
  • all bits should be inverted and to it '1' added to build the value of C
  • 0000000000011101+0000000000000001 == 0000000000011111

Answer

scary_jeff picture scary_jeff · Oct 21, 2015

to_unsigned is for converting between different types:

signal i : integer := 2;
signal u : unsigned(3 downto 0);

...

u <= i;  -- Error, incompatible types
u <= to_unsigned(i, 4); -- OK, conversion function does the right thing

If you try to convert a negative integer, this is an error.

u <= to_unsigned(-2, 4); -- Error, does not work with negative numbers

If you simply want to invert an integer, i.e. 2 becomes -2, 5 becomes -5, just use the - operator:

u <= to_unsigned(-i, 4);  -- OK as long as `i` was negative or zero

If you want the absolute value, a function for this is provided by the numeric_std library.

u <= to_unsigned(abs(i), 4);