Search code examples
vhdl

Sign function in VHDL


I'm currently working on a design in which I need to do sgn(x)*y, where both x and y are signed vectors. What is the preferred method to implement a synthesizable sgn function in VHDL with signed vectors? I would use the SIGN function in the IEEE.math_real package but it seems like I won't be able to synthesize it.


Solution

  • You don't really need a sign function to accomplish what you need. In numeric_std the leftmost bit is always the sign bit for the signed type. Examine this bit to decide if you need to negate y.

    variable z : signed(y'range);
    ...
    
    if x(x'left) = '1' then -- Negative
      z := -y; -- z := -1 * y
    else
      z := y; -- z := 1 * y
    end if;
    
    -- The same as a VHDL-2008 one-liner
    z := -y when x(x'left) else y;
    

    Modify as needed if you need to do this with signal assignments.