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