 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C# program to count total set bits in a number
The number for our example is 11 i.e. binary −
1101
The total set bits are 3 in 1101; to find it, use a loop till it’s not equal to 0. Here, our num is 11 i.e. decimal −
while (num>0) {    cal += num & 1;    num >>= 1; } Example
To count total set bits in a number, use the following code.
using System; public class Demo {    public static void Main() {       int cal = 0;       // Binary is 1011       int num = 11;       while (num>0) {          cal += num & 1;          num >>= 1;       }       // 1 bits in 1101 are 3       Console.WriteLine("Total bits: "+cal);    } }  Output
Total bits: 3
Advertisements
 