前言
本文将介绍如何使用Verilog语言检测16位二进制数中0的个数,和第一个1之前0的个数。
代码
.v文件
module 16bit_check (input [15:0] num,
output reg[4:0] res1,res2);
integer i,j=0,cnt1,cnt2;
reg [15:0] temp1,temp2;
always@(num)
begin
cnt2=0;
temp1=num;
for(i=0;i<16;i=i+1)
begin
if(!temp1[i])
cnt2=cnt2+1;
end
res2=cnt2;
begin
cnt1=0;
temp2=num;
while(temp2&&(temp2[0]==0))
begin
cnt1=cnt1+1;
temp2=temp2>>1;
end
res1=cnt1;
end
end
endmodule
vt文件
`timescale 1 ns/ 1 ps
module 16bit_check_vlg_tst();
reg [15:0] num;
wire [4:0] res1;
wire [4:0] res2;
16bit_check i1 (
.num(num),
.res1(res1),
.res2(res2)
);
initial
begin
num='b0000_1100_0000_0000;
end
always
begin
#50 num=num+1;
$stop;
end
endmodule
仿真波形图
总结
本代码的难点在于第一个1前面0的个数检测,好在Verilog支持while语句,可以利用while语句设置两个循环条件:数的最低位为零且每次右移后数不为0,这里第二个条件为防止输入为16个0的情况。