Banerjee
Banerjee

Reputation: 41

Adding two vectors of 5 bit numbers in vhdl

I am new to vhdl, I am trying to add 2 vectors of 5 bit unsigned numbers.In the following code the signal firstsum gives proper output in waveform but the vector sum does not show any output, I am using quartus ii. What is the error in this code?

library IEEE;
use IEEE.STD_LOGIC_1164.all;
use ieee.numeric_std.all;

package UVEC is 
subtype UINT5 is std_logic_vector (4 downto 0);
type UVEC5 is array (2 downto 0) of UINT5;
subtype UINT6 is std_logic_vector (5 downto 0);
type UVEC6 is array (2 downto 0) of UINT6;
end UVEC;

library IEEE;
use IEEE.STD_LOGIC_1164.all;
use ieee.numeric_std.all;
use work.UVEC.all;

entity FP_Vecsum1 is
    port(
    a,b : in UVEC5;
    sum : out UVEC6;
    firstsum : out UINT6
    );
end FP_Vecsum1;

architecture FP_Vecsum1_MX of FP_Vecsum1 is
begin


    firstsum <= std_logic_vector(('0'&unsigned(a(0)))+('0'&unsigned(b(0))));
    sum(0) <= std_logic_vector(('0'&unsigned(a(0)))+('0'&unsigned(b(0))));
    sum(1) <= std_logic_vector(('0'&unsigned(a(1)))+('0'&unsigned(b(1))));
    sum(2) <= std_logic_vector(('0'&unsigned(a(2)))+('0'&unsigned(b(2))));

end FP_Vecsum1_MX;

Upvotes: 0

Views: 898

Answers (1)

donkalika
donkalika

Reputation: 11

welcome to the VHDL world.

I also haven't found anything wrong with your code, but you can try the following, maybe this will help:

first, try to cast the signals to unsigned in the beginning of your architecture, before doing the math:

a_us(0) <= unsigned(a(0));
a_us(1) <= unsigned(a(1));
a_us(2) <= unsigned(a(2));

this is quite convenient: if your ports to the outside world are neutral vectors, the math inside your component is either signed or unsigned. do the conversion once, and you're free.

second, instead of manually doing the sign extension, now that you have determined your vectors as unsigned, you can use resize function to automatically set the summed vectors to the result length:

sum(0) <= std_logic_vector(resize(a_us(0),sum(0)'length) + resize(b_us(0),sum(0)'length));

you can also do a little trick by adding a zero with a relevant vector width:

sum(0) <= std_logic_vector( to_unsigned(0,sum(0)'length) + a_us(0) + b_us(0) );

it might look a little longer, but in my opinion it's a more robust code.

hope this helps, ilan.

Upvotes: 1

Related Questions