How to use signed variable in System Verilog

Author: monokent

Example 1

In verilog, signed data is in the form of two's complement.
In this example, we declare variable as "signed" type, and constant integer as "sd".

logic signed [35:0] c0, c1;
logic signed [17:0] a0, a1;
always@(*) begin
    c0 <= a0 * 18'sd2017;
    c1 <= a1 * -18'sd2016;
end

In above, "sd" means signed decimal.

Example 2

In example 1, if we write

c1 <= a1 * -18'd2016;

The result will be wrong, for verilog treats -18'd2016 as unsigned and therefor it changed to a positive value.
And what if we write

c0 <= a0 * 18'd2017

The result is also incorrect, because if there is a unsigned operand in an expression then all the operands will be converted into unsigned compulsorily. As a result, the negative a0 will be converted into a positive value.

Example 3

Right shift a signed variable

assign c0_normal = c0 >>> 17;

">>>" is arithmetic right shift for signed variable.

Example 4

What is the result of each expression ?

integer a;
a = -18 / 3;     // -6
a = -6'd18 / 3;  // 23
a = -6'sd18 / 3  // -6
a = -5'sd18 / 3  // (14/3)=4
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容