EmbDev.net

Forum: FPGA, VHDL & Verilog Short VHDL for loop code i dont understand


von Kasper (Guest)


Rate this post
useful
not useful
Hey,

I do understand how to convert a binary number into a decimal number but 
the following code thats supposed to do that doesnt make sense. I mean 
lets sat we have a binary number 10, then v(i) would be 0, so result 
stays 0. Upon the next iteration v(i) will be 1 so result will be 0 + 1 
. The loop stops and the function will return the value of result which 
is 1 and not 2 which is the value of the binary number put into the 
function. Could someone tell me why I am wrong? This code comes with a 
university assignment so it should be correct. Thanks. :)

------------------------------------------------------------------------ 
-------
-- convert std_logic vector v to natural
------------------------------------------------------------------------ 
-------

FUNCTION s2n(v: std_logic_vector)
RETURN natural IS
VARIABLE result: natural := 0;
BEGIN
    FOR i IN v'range LOOP
            result := result * 2;
            IF v(i) = '1' THEN
                    result := result + 1;
            END IF;
    END LOOP;
    RETURN result;
END s2n;

von Lothar M. (Company: Titel) (lkmiller) (Moderator)


Rate this post
useful
not useful
Lets define a
signal x : std_logic_vector(1 downto 0);
Then
x'range will result in (1 downto 0)

And so the code
    FOR i IN v'range LOOP
will result in
    FOR i IN 1 downto 0 LOOP

And now, try it once more. First index now is number 1, the second cycle 
is index 0...


The major problem of this "university assigned" code is, that it 
implicitly assumes, that the vector is ranged with a downto.
It will not work as expected with this vector:
signal x : std_logic_vector(0 to 1);

Please log in before posting. Registration is free and takes only a minute.
Existing account
Do you have a Google/GoogleMail account? No registration required!
Log in with Google account
No account? Register here.