问题描述
当我尝试模拟以下代码时,出现了一个非常奇怪的行为。 reg
in
实际上显示的值大于系统函数 $urandom_range
中给定的范围。我已经看到当我尝试使用无符号 reg
并在给定函数的范围内使用负值时会发生这种行为。代码如下。
注意:在下面的模拟结果中,我们可以看到有大于 8 的值,例如“15”和“12”。
`timescale 1ns/1ns
module test_tb();
parameter IN_SIZE = 5;
reg signed [IN_SIZE-1 : 0] in;
reg clk;
initial begin
clk = 0;
forever clk = #5 ~clk ;
end
always @(posedge clk) begin
in = $urandom_range(-16,8);
$display("The generated number is %d ",in);
end
endmodule
#模拟结果
生成的数字是 15
生成的数字是 4
生成的数字是 4
生成的数字是 4
生成的数字是-16
生成的数字是 15
生成的数字是-2
生成的数字是 12
生成的数字是 8
生成的数字是 1
解决方法
IEEE Std 1800-2017 声明 $urandom_range
如下:
function int unsigned $urandom_range( int unsigned maxval,int 无符号 minval = 0 );
这表明函数的输入必须是无符号值。因此,-16 是非法的。该函数返回意外值也就不足为奇了。不幸的是,我尝试过的模拟器都没有产生错误或警告。
要获得 -16 到 8 范围内的有符号值,请使用正值并减去 16。更改:
in = $urandom_range(-16,8);
到:
in = $urandom_range(24) - 16;