用verilog HDL循环语句来统计8位二进制中含1的数量

 我来答
ytchuang713
2011-04-01 · 超过19用户采纳过TA的回答
知道答主
回答量:39
采纳率:0%
帮助的人:31.5万
展开全部
hi,

Please see the followings, and do not hesitate to tell me your question,
thanks.

module count_one
(
num1,
num1_vld,

in8,
clk,
rst_n
);

output [3:0] num1; //how many 1 in the signal
outptu num1_vld ; //num1 is valid only when the signal = 1

input [7:0] in8 ;//input 8-digit signal
input clk;
input rst_n;

//apply a count to count 8 periodically
reg [2:0] sht_cnt ;

//3 bit count to count 0~7, so sht_cnt wrap around naturally...
//i.e. sht_cnt will count like this: 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2,...
always@(posedge clk or negedge rst_n)
begin
if(~rst_n)
sht_cnt <= 3'b0 ;
else
sht_cnt <= sht_cnt + 3'b1 ;
end

//use shift count (sht_cnt) to select which digit you like to check
reg bit_sel ;

always@(*)
begin
case(sht_cnt)
3'h0: bit_sel = in8[0] ;
3'h1: bit_sel = in8[1] ;
3'h2: bit_sel = in8[2] ;
3'h3: bit_sel = in8[3] ;
3'h4: bit_sel = in8[4] ;
3'h5: bit_sel = in8[5] ;
3'h6: bit_sel = in8[6] ;
3'h7: bit_sel = in8[7] ;
default: bit_sel = 1'bx ;//it's only for debug purpose
end

//the signal is used to check when to latch sum of in8 ;
wire num1_vld_p;

assign num1_vld_p = (sft_cnt == 3'h7);

reg [3:0] num1 ;

always@(posedge clk or negedge rst_n)
begin
if(rst_n)
num1 <= 3'b0 ;
else
num1 <= (sft_cnt == 3'h0) ? sel_cnt : (num1 + {2'b0,sel_cnt}) : num1 ;
end

reg num1_vld ;

always@(posedge clk or negedge rst_n)
begin
if(!rst_n)
num1_vld <= 1'b0 ;
else
num1_vld <= num1_vld_p ;
end

endmodule

The code is a bit long, so syntax error may occur, please help fix them...^^
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式