VHDL - Adding two 8-bit vectors into a 9-bit vector

krb686 picture krb686 · Nov 26, 2013 · Viewed 25k times · Source

This is a pretty simple question, but I haven't been able to make this work yet, nor has any searching on google or here turned up anything really useful.

All I'm trying to do is add two 8-bit vectors and store the result in a 9-bit vector.

signal operand1, operand2 : STD_LOGIC_VECTOR(7 downto 0);

signal sum : STD_LOGIC_VECTOR(8 downto 0);

sum <= operand1 + operand2;

However I get the warning:

Width mismatch. <sum> has a width of 9 bits but assigned expression is 8-bit wide.

Shouldn't VHDL have some sort of built in routine to know that an extra bit is necessary for addition overflow?

I have these packages included:

use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

Perhaps STD_LOGIC_VECTOR is always signed? If so, then I need to define them explicity as unsigned?

Answer

rick picture rick · Nov 26, 2013

If your goal is to do arithmetic on your signals, get into the habit of declaring them with better-suited types for the job: unsigned or integer are good choices in your case.

Note that to prevent overflow you must concatenate a leading '0' to each operand, instead of doing it to the result:

sum <= ('0' & operand1) + ('0' & operand2);