统计1的个数(Verilog)

RTL代码:

module test(
	input [7:0]data_in,
	output [3:0]out
);

// 写法一:
	reg [3:0]width;
	reg [3:0]cnt;
	
	always@(data_in)begin
		cnt = 'd0;
		for(width = 0; width < 8; width = width + 1)begin
			if(data_in[width])
				cnt = cnt + 1'b1;
			else
				cnt = cnt;
		end
	end
	
	assign out = cnt;

// 写法二:
//	assign out = data_in[0] + data_in[1] + data_in[2] + data_in[3] + data_in[4] + data_in[5] + data_in[6] + data_in[7];

endmodule


仿真代码:

`timescale 1ns/1ns
module test_tb;

	reg [7:0]data_in;
	wire [3:0]out;
	
	test test_inst(
		.data_in		(data_in	),
		.out			(out		)
);

	
	
	initial begin
		data_in = 8'b0000_0000;
		#200;
		data_in = 8'b1111_0010;
		#200;
		data_in = 8'b1100_0010;
		#200;
		data_in = 8'b1111_1111;
		#200;
		$stop;
	
	end
	
	
endmodule


modelsim仿真:
统计1的个数(Verilog)_第1张图片

你可能感兴趣的:(FPGA笔试题,FPGA)