Forum Discussion

Altera_Forum's avatar
Altera_Forum
Icon for Honored Contributor rankHonored Contributor
13 years ago

Subtracting from a std_logic_vector

library IEEE;

use IEEE.std_logic_1164.all;

use IEEE.std_logic_arith.all;

use IEEE.std_logic_unsigned.all;

.

.

.

signal count_val : std_logic_vector(5 downto 0) := "000000";

.

.

now what should the answer be if I do try to subtract 1 from the logic vector when it is 0?

What shall the value be if I add 1 to it when its value is already "111111"?

4 Replies

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    std_logic_vector is undefined in terms of mathematical value until you either ask compiler to interpret as either signed or unsigned.

    if signed: 000000 + 1 => 000001

    000000 - 1 => 111111 (-1)

    if unsigned: 000000 + 1 => 000001 same as above

    0000000 -1 => illegal (-1), what you get is up to tool if allowed

    if the tool does let you add/subtract on std_logic_vector then it is using default and is not safe.
  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    Over/underflowing is a perfectly normal behavior when using a bit type, and no tool should throw an error (I dont know how you would synthesis a checker for it anyway without specifically building one).

    Integer on the other hand will not overflow in simulation, you'll get an error, but on an FPGA it will overflow.
  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    I was trying to create an up/down counter. I am getting confused what will come if I do (-1) on std_logic_vector when it already is equal to "000000". What value should I expect to be detected if do (-1) and than try to do unsigned() of the result in an if statement?

  • Altera_Forum's avatar
    Altera_Forum
    Icon for Honored Contributor rankHonored Contributor

    I agree with Tricky. Underflow and overflow occurs naturally when perform add and substract operations. If you perform a simulation with Model Sim you see that "0000" - "0001" gives "1111" ( underflow ). Try the testbench:

    uut : entity work.sumador_2

    port map(

    a => tb_a,

    s => tb_s

    );

    process

    begin

    wait for 1ms;

    for i in 0 to 15 loop

    tb_a <= std_logic_vector(to_unsigned(i, 4));

    wait for 1ms;

    end loop;

    assert false

    report "Fin de la simulacion"

    severity failure;

    end process;

    Where sumador_2 is:

    architecture data_flow of sumador_2 is

    begin

    s <= std_logic_vector( unsigned(a) - "0001");

    end architecture data_flow;