Ka S Per
Ka S Per

Reputation: 1

Short VHDL for loop code i dont understand

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;

Upvotes: 0

Views: 792

Answers (1)

Martin Thompson
Martin Thompson

Reputation: 16832

The 'range loop works from left to right. The convention is for the most-significant bit to be on the left

By decoding that first, the *2 operation gets run most times on the MSB as you'd expect.

(BTW, if you want the range to go the other way for some reason, you can use the 'reverse_range attribute)

Upvotes: 1

Related Questions