Open In App

C++ __builtin_popcount() Function

Improve
Improve
Like Article
Like
Save
Share
Report

__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. In other words, it counts the number of 1’s in the binary form of a positive integer.

Syntax:

__builtin_popcount(int number);

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

Return Value: Number of set bits in the given number.

Illustration:

Input: n = 5
binary value of 5: 101
Output: 2

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

Time Complexity(b), where b is the number of bits.
Auxiliary Space: O(1)

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

__builtin_popcount() 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


Last Updated : 05 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads