R.Mckemey
R.Mckemey

Reputation: 355

Indexing of original vector in a function in VHDL

I want to write a function in VHDL which is given the top few bits of a std_logic_vector and does stuff to them but it seems to be that the indexing of my function still starts counting at the bottom of the whole vector.

I can get around this by first assigning my vector to a temporary signal and using that but I'm worried that I don't understand what's going on here.

Could someone explain why a and b don't get the same output in the below?

architecture rtl of inds is
  function top_bit (c : std_logic_vector) return std_logic is
  begin
    return c(c'length-1);
  end top_bit;
  signal temp : std_logic_vector(2 downto 0);
begin
  temp <= input(3 downto 1);
  a <= top_bit(temp);
  b <= top_bit(input(3 downto 1));
end rtl;

If you give them the input "0100", you get a='0', b='1'.

If you give them the input "1000", you get a='1', b='0'.

So a=temp(2)=input(3) and b=input(2) which is input("length of c" -1).

I don't think this makes sense, can someone justify it for me.

Edit: if you replace the declaration line with:

function top_bit (c : std_logic_vector(2 downto 0)) return std_logic is

then it works as I'd expect. I suppose the vector c takes it's indexing from the vector it's given.

I'd like to see a function which takes an arbitrary slice of a vector and returns the top bit of that slice.

Upvotes: 0

Views: 637

Answers (2)

PlayDough
PlayDough

Reputation: 1128

The issue, is that c'length returns the length of the vector which is not necessarily a valid index. For example, say I declared the following signal:

signal temp : std_logic_vector(7 downto 4);

This would cause a range error calling top_bit. As you note in your comment on scary_jeff's answer, not all vectors are x downto 0. They could be x downto y. Or they could even by 0 to x or x to y. Assuming that c'length-1 is the top bit is only true if c is declared as std_logic_vector(N-1 downto 0) (which you discovered in your answer).

Just as a clarification. scary_jeff's answer is the correct way. However, you need to resolve what is meant by "top_bit". What if you are given a to vector, such as:

signal temp : std_logic_vector(4 to 7)

What is top bit? Bit 4 or bit 7? If you use 'high, you'll get bit 7. Is this the top bit? If you want bit 4 to be the top bit, you'll need to use 'low.

Upvotes: 1

scary_jeff
scary_jeff

Reputation: 4374

You are using the 'length attribute, where you could be using 'high. I think this would do what you're asking for.

I've got a print out on my wall of the table here http://www.csee.umbc.edu/portal/help/VHDL/attribute.html as a reference for what attributes are available.

Upvotes: 2

Related Questions