Nikita Malyshev
Nikita Malyshev

Reputation: 69

Unsigned in VHDL

I have a VHDL code. Modelsim give me error

"Length of expected is 32; length of actual is 31"

How to write code, that it was correct and I not to write length of vectors. I want that works like in Verilog: Verilog

reg [30:0] smth1 = 2735*12;
reg [15:0] smth2 = 12*11;
reg [31:0] smth1_s; 
always (*)
begin 
smth1_s <= smth1+smth2;
end 

VHDL:

library ieee; 
    use ieee.std_logic_1164.all; 
    use ieee.std_logic_unsigned.all;
    use ieee.numeric_std.all; 

entity top is 
end entity; 

architecture top of top is  
    signal smth1 : unsigned(30 downto 0) := to_unsigned(2735,16) * to_unsigned(12,15);      --reg [31:0] smth1 = 12'hAAF * 12; 
    signal smth2 : unsigned(15 downto 0) := to_unsigned(12,16) / to_unsigned(11,16);        --reg [15:0] smth2 = 12*11;                 
    signal smth1_s : unsigned(31 downto 0);     

begin                           
        smth1_s <= smth1 + smth2;                               
end architecture; 

Upvotes: 1

Views: 2189

Answers (1)

Morten Zilmer
Morten Zilmer

Reputation: 15924

The length of the result from + is the longest of the two arguments, thus 30 bits, which is assigned to a 31-bit destination, thus the error.

Resizing, which adapt to argument as either signed or unsigned, can be used, but you need to resize before the addition in order to extend the result for the carry bit, as I assume is the intention.

So generic and maintainable code may be like, where you may add a suitable comment to describe the purpose of the resizing:

smth1_s <= resize(smth1, smth1_s'length) + resize(smth2, smth1_s'length);

A good synthesis tool, like most today, will optimize the circuit so only the minimum number of full adders are used, even through it looks like more bits are being added due to the resize.

Upvotes: 1

Related Questions