Today we are going to see the methods of counting number of ones in given decimal number.
Method 1:
By using foreach loop.
module TB;
bit[3:0] x;
int cnt;
initial begin
cnt=0;
x=10;
foreach(x[i])
cnt+=x[i];
$display("No of ones %0d",cnt);
end
endmodule
Foreach loop applicable only for the data type of bit,wire,reg,logic or in other words it supports only packed arrays. instead of bit[3:0] x if we put int we will get the compilation error.
Method 2:
By using while loop,
module TB;
int x;
int cnt;
initial begin
cnt=0;
x=$urandom;
while(x) begin
x=x&(x-1);
cnt++;
end
$display("No of ones %0d",cnt);
end
endmodule
Method 3:
By using while loop in other form,
module TB;
int x;
int cnt;
initial begin
cnt=0;
x=$urandom;
while(x) begin
cnt+=x&1;
x>>=1;
end
$display("No of ones %0d",cnt);
end
endmodule
Method 4:
By using $countones function.
module TB;
int x;
int cnt;
initial begin
x=$urandom;
cnt=$countones(x);
$display("No of ones %0d",cnt);
end
endmodule
Hope this code will be useful to everyone !!!
Giving feedback is more precious than writing a article!!! 😊😊😊😊😊
Always welcome both positive and negative feedback's !!!
Feel free to post query related SV & UVM
Good..It was very useful
ReplyDeleteThanks for the explanation. It's really good.
ReplyDeleteGood. It was useful
ReplyDeleteSuper! Complex problem solved with simple explanation! Keep doing..
ReplyDeleteGood effort!! Keep sharing!
ReplyDeleteKeep going!!!
ReplyDeleteGreat effort.. Keep going.. Nice explanations..
ReplyDeleteGood effort
ReplyDeleteGreat work. Very much useful for Newbies.
ReplyDeleteGood try for the all possible ways. Keep up your ramp.
ReplyDelete