Search code examples
vhdl

Divide negative number in VHDL by shifting


I have a negative number(MSB=1). How can I divide the number by, say 2 , by shifting in VHDL.

Eg. shifting -6 should give me 2.

How can I generalize the division/shift eg:- -6 -> -3 6 -> 3


Solution

  • For division by 2 of numbers (both negative and positive) in two's complement using ieee.numeric_std.signed it can be done using shift with:

    res <= std_logic_vector(shift_right(signed(arg), 1));
    

    The shift_right with signed argument will do arithmetic shifting, thus useful for division by 2 with a single bit shifted.

    As MatthiasB points out in the comment, then division can also be used, with:

    res <= std_logic_vector(signed(arg) / 2);
    

    The difference in operation is:

    • Shift (shift_right): Round down, thus -7 / 2 = -4
    • Division (/): Rounds towards zero, thus -7 / 2 = -3

    The difference in implementation:

    • Shift (shift_right): Zero cost in size and speed, since done with wiring only
    • Division (/): Some cost in size and speed, since logic operations are required for rounding