std::has_single_bit in C++ 20

In C++ 20, the std::has_single_bit function is a predefined function that is used to check if a given value is an integral power of two or not. This function is defined in the <bit> header file.

The std::has_single_bit() function works by checking whether a given integer has exactly one bit set to ‘1’ in its binary representation because the numbers that are powers of two have only one bit set in their binary form. For example, 2 is 10 in binary, 4 is 100, 8 is 1000 and so on.

Syntax of std::has_single_bit() in C++

std::has_single_bit(num)

Parameters of has_single_bit()

This function accepts a single parameter:

  • num: It is an unsigned integer type value that we want to check.

Return Value has_single_bit()

The std::has_single_bit function return:

  • true if x is an integral power of two(has exactly one bit set in its binary representation).
  • Otherwise, it returns false.

Example of std::has_single_bit in C++

Input:
Num: 4

Output:
4 has a single bit set.

Explanation : Binary representation of 4 is 0100 which has exactly one set bit.
Therefore, 4 = 2^2 which is a integral power of two.

The below example demonstrates how we can use has_single_bit() function to check if a given value is an integral power of two in C++.

C++
// C++ program to demonstrate the use of has_single_bit()
// function
#include <bit>
#include <iostream>
using namespace std;

int main()
{

    // Declare and initialize an unsigned integer variable.
    unsigned int x = 16;

    // Check if x has a single bit set using has_single_bit.
    if (has_single_bit(x)) {
        // If true, print that x has a single bit set.
        cout << x << " has a single bit set." << endl;
    }
    else {
        // If false, print that x does not have a single bit
        // set.
        cout << x << " does not have a single bit set."
             << endl;
    }
    return 0;
}


Output

16 has a single bit set.

Time Complexity : O(1), function has_single_bit() is a constant-time operation
Auxilliary Space: O(1)

Note: The has_single_bit() function only works with unsigned integer types. Always make sure to provide unsigned integer as an input to this function. Failing to do so will result in a compiler error.



Contact Us