verilog 中signed数据处理,负数
verilog中支持signed 数据类型,即支持负数的处理。此时参与运算的各个数均应是signed类型,且数据位宽相同(若位宽不相同,则应手动将其扩展为位宽相同,具体做法就是将最高位的符号位进行扩展),且运算结果要比运算数的位数大以防止溢出。以下用两个小例子进行说明。细节可参考此篇文章: http://www.cnblogs.com/oomusou/archive/2009/10/31/verilog_signed_overflow.html
Examp 1.
-
module top(clk,a,b,c);
-
input clk;
-
input signed [7:0] a;
-
input signed [7:0] b;
-
output reg signed [8:0] c;
-
-
always@(posedge clk)
-
begin
-
if((a-b)< 0)
-
c <= b - a;
-
else if ((b-a)==0)
-
c <= 0;
-
else
-
c <= a - b;
-
end
-
-
endmodule
testbench:
-
module sim_top ;
-
-
reg clk;
-
reg signed [7:0] a;
-
reg signed [7:0] b;
-
wire signed [8:0] c;
-
-
initial begin
-
clk= 0;
-
a=0;
-
b=8;
-
forever clk=#5 ~clk ;
-
end
-
-
always@(posedge clk)
-
begin
-
a<=a+2;
-
b<=b+1;
-
end
-
-
top my_top(
-
.clk(clk),
-
.a(a),
-
.b(b),
-
.c(c));
-
-
endmodule
仿真结果图:
Examp 2:
-
module top(clk,a,b,c);
-
input clk;
-
input signed [7:0] a;
-
input signed [7:0] b;
-
output reg signed [8:0] c;
-
-
always@(posedge clk)
-
begin
-
/* if((a-b)< 0)
-
c <= b - a;
-
else if ((b-a)==0)
-
c <= 0;
-
else*/
-
c <= a - b;
-
end
-
-
endmodule
testbench同上。
仿真结果: