Answers for "how to count number of bits using bitwise operations"

3

count number of bits set in a number

int count_one (int n)
        {
            while( n )
            {
            n = n&(n-1);
               count++;
            }
            return count;
    }
Posted by: Guest on August-13-2021
4

bitwise count total set bits

//WAP to find setbits (total 1's in binary ex. n= 5 => 101 => 2 setbits
int count{}, num{};
  cin >> num;

  while (num > 0) {
    count = count + (num & 1); // num&1 => it gives either 0 or 1
    num = num >> 1;	// bitwise rightshift 
  }

	 cout << count; //count is our total setbits
Posted by: Guest on September-30-2020

Code answers related to "how to count number of bits using bitwise operations"

Browse Popular Code Answers by Language