shift a std_logic_vector of n bit to right or left

Mazzy picture Mazzy · Jan 26, 2012 · Viewed 250.4k times · Source

I have a vector signal tmp : std_logic_vector(15 downto 0)

I have to shift it to left or right of n bit. how can I realize this operation. I thought to concatenation operation but I didn't know how use it.

Answer

Martin Thompson picture Martin Thompson · Jan 27, 2012

Use the ieee.numeric_std library, and the appropriate vector type for the numbers you are working on (unsigned or signed).

Then the operators are sla/sra for arithmetic shifts (ie fill with sign bit on right shifts and lsb on left shifts) and sll/srl for logical shifts (ie fill with '0's).

You pass a parameter to the operator to define the number of bits to shift:

A <= B srl 2; -- logical shift right 2 bits

Update:

I have no idea what I was writing above (thanks to Val for pointing that out!)

Of course the correct way to shift signed and unsigned types is with the shift_left and shift_right functions defined in ieee.numeric_std.

The shift and rotate operators sll, ror etc are for vectors of boolean, bit or std_ulogic, and can have interestingly unexpected behaviour in that the arithmetic shifts duplicate the end-bit even when shifting left.

And much more history can be found here:

http://jdebp.eu./FGA/bit-shifts-in-vhdl.html

However, the answer to the original question is still

sig <= tmp sll number_of_bits;