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

von Kasper (Guest)

Rate this post
0 useful
not useful

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;
    FOR i IN v'range LOOP
            result := result * 2;
            IF v(i) = '1' THEN
                    result := result + 1;
            END IF;
    RETURN result;
END s2n;

von Lothar M. (lkmiller) (Moderator)

Rate this post
0 useful
not useful
Lets define a
signal x : std_logic_vector(1 downto 0);
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);


Entering an e-mail address is optional. If you want to receive reply notifications by e-mail, please log in.

Rules — please read before posting

  • Post long source code as attachment, not in the text
  • Posting advertisements is forbidden.

Formatting options

  • [c]C code[/c]
  • [vhdl]VHDL code[/vhdl]
  • [code]code in other languages, ASCII drawings[/code]
  • [math]formula (LaTeX syntax)[/math]

Bild automatisch verkleinern, falls nötig
Note: the original post is older than 6 months. Please don't ask any new questions in this thread, but start a new one.