Sunday, July 19, 2020

Count the number of ones in a given decimal number with and without using countones function in system verilog

Hi Everyone!,
 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




10 comments:

`define Macro usage in System Verilog

 Hi Everyone !!! In this blog we are going to see the usage of `define macro in System Verilog. A text macro substitution facility has been ...