
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
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
- Related Articles
- Java program to count total bits in a number
- C# program to count total bits in a number
- Python program to count total set bits in all number from 1 to n.
- Write a python program to count total bits in a number?
- Count total bits in a number in C++
- Program to count total number of set bits of all numbers in range 0 to n in Python
- Python Program to Count set bits in an integer
- Java Program to Count set bits in an integer
- How to count set bits in a floating point number in C?
- C/C++ Program to Count set bits in an integer?
- Golang Program to count the set bits in an integer.
- C/C++ Program to the Count set bits in an integer?
- Python Count set bits in a range?
- Check if bits of a number has count of consecutive set bits in increasing order in Python
- Count set bits in a range in C++

Advertisements