Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

C++ __builtin_popcount() Function

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

__builtin_popcount()  is a built-in function of GCC compiler. This function is used to count the number of set bits in an unsigned integer. 

Syntax:

__builtin_popcount(int number);

Parameter: This function only takes unsigned or positive integers as a parameter.

Time Complexity:O(1)

Auxiliary Space: O(1)

Input: n = 4
binary value of 4: 100
Output: 1

Example:

C++




// C++ code to demonstrate the
// __builtin_popcount function
#include <bits/stdc++.h>
 
using namespace std;
 
int main()
{
 
    int n = 4;
 
    // Printing the number of set bits in n
    cout << __builtin_popcount(n);
 
    return 0;
}

Output

1

What will happen if the data type is of type long long?

__builtin_popcountll is a GCC extension that is used to count the number of set bits in long long data types. 

Syntax:

__builtin_popcountll(long long number);

Example:

C++




// C++ code to demonstrate the
// __builtin_popcount function
#include <bits/stdc++.h>
 
using namespace std;
 
int main()
{
 
    long long n = 1e15;
 
    // Printing the number of set bits in n
    cout << __builtin_popcountll(n);
 
    return 0;
}

Output

20
My Personal Notes arrow_drop_up
Last Updated : 20 Feb, 2023
Like Article
Save Article
Similar Reads
Related Tutorials