问题描述
作为学习如何在Verilog中编写函数的任务,我试图编写一个仅计算给定向量中的个数的函数:
module m ();
parameter n = 4;
function integer count_ones (input [n-1:0] a);
for (integer i = 0 ; i<n ; i=i+1)
begin
if (a[i] ==1'b1)begin
count_ones=count_ones+1;
end
end
endfunction
initial begin
reg [3:0] a = 4'b1;
integer result = count_ones (a);
$display("output is ",result);
end
endmodule
解决方法
您将count_ones
声明为类型integer
,它是4状态类型,其默认值为x
。另外,count_ones=count_ones+1;
保持count_ones
等于x
。
您应该在函数内部初始化count_ones
。
function integer count_ones (input [n-1:0] a);
count_ones = 0;
请记住,有一个内置的$countones
系统功能。请参阅IEEE Std 1800-2017第20.9节位矢量系统功能。