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.
-
Not posting as an answer since I don't know VHDL, but isn't the sign of a number typically represented by its high-order bit? The sign of the product of two numbers is just the XOR of their sign bits.– WyzardCommented Oct 11, 2014 at 19:15
-
Maybe I'm missing something, but why not test with x<0? Then calculate as shown in Kevin's answer: -y when (x<0) else y– rickCommented Oct 12, 2014 at 17:26
-
No you're both right, I was just making things complicated for myself. I don't know what I was thinking. Thank you.– AmmarCommented Oct 12, 2014 at 20:02
2 Answers
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.
-
Yes this is exactly what I should do. I was making things too complicated for some reason. Thank you!– AmmarCommented Oct 12, 2014 at 19:58
If you are only interested in using the sign function, the best option is that you define a block in your program whose input is the signed vector x and its output is another bit vector whit the value of the sign.
The way of designing that block is taking the most significative bit of the vector as it indicates the sign. Then, if you write that the output must be one(1(0), others->(0) or how it writes) if that bit is 0 (positive or null value), or every bit are ones(others->(1)) if that bit is 1 (negative value).
You can also define that if input value is 0, the output will also be a 0.