Search code examples
for-loopvectorvhdltypeconverter

Convert element from std_logic_vector to integer vhdl


I am working on a function that takes in a signal and adds it into a vector.

Once enough signals have been added, in my case 4, then I loop through the vector and add it to an integer variable in my process.

I am having trouble converting the individual elements into integers.

I tried using to_integer(unsigned(myVector)), but this was a binary to decimal conversion.

I just want it so that when i loop through my vector like this:

for i in 0 to myVector'length loop
    Sum := Sum + to_integer(myVector(i));
end loop;

that a bit value of 1 or 0 gets converted to a 1 or 0 that I can use to add to my sum.

Any ideas?

Thanks

PS - myVector is a signal, Sum is an integer variable in my process. If there is no simple way, how else can I do this?


Solution

  • Assuming you want to count the ones in a numeric_std_unsigned, the problem is simply that to_integer needs to work on a vector (an unsigned) while myVector(i) is a bit (std_logic)

    The following creates a 1-bit unsigned which to_integer should be happy with.

    for i in 0 to myVector'length loop
        Sum := Sum + to_integer(myVector(i downto i ));
    end loop;
    

    Alternatively, if the synthesis tool doesn't like dynamically slicing myVector in a loop,

    for i in 0 to myVector'length loop
        if myVector(i) = '1' then
            Sum := Sum + 1;
        end if;
    end loop;
    

    will do.

    Also note that the loop bounds probably have a range error... 0 to length is probably 1 iteration more than you have elements - ASSUMING the elements actually started at 0, which is quite an assumption.

    for i in myVector'low to myVector'high loop
    

    is preferred...