编写一个简单的函数来计算向量中的个数
Writing a simple function to count number of ones in a vector
作为学习如何在 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
结果显示为x
。那么这段代码中的错误是什么?
您将 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;
请记住,有一个 built-in $countones
系统函数。请参阅 IEEE Std 1800-2017,第 20.9 节 位向量系统函数。
作为学习如何在 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
结果显示为x
。那么这段代码中的错误是什么?
您将 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;
请记住,有一个 built-in $countones
系统函数。请参阅 IEEE Std 1800-2017,第 20.9 节 位向量系统函数。