Problem 40 Combinational for-loop: 255-bit population count
设计电路来计算输入矢量中 ’1‘ 的个数,题目要求建立一个255bit输入的矢量来判断输入中 ’1‘ 的个数。
module top_module( input [254:0] in, output [7:0] out ); always@(in)begin out = 'd0; for(int i = 0; i <= 254; i = i + 1)begin if(in[i]) out = out + 1'b1; else out = out; end end endmodule
这里务必小心的一点在于,对输出端out累进赋值之前,应该先将其赋初值为0.
另外上面代码也可以写成这种形式
always@(in)begin out = 8'd0; for(int i = 0; i <= 254; i = i + 1)begin out = out + in[i]; end end
小梅哥(时序逻辑计数器)
always@(posedge clk or negedge reset_n)
上面代码中posedge、negedge、or是系统已经声明的符号,clk、reset_n是人为声明的变量。
整个的效果是:当clk或reset_n发生变化时触发这一always模块。