bitset test() in C++ STL

bitset::test() is an inbuilt function in C++ STL which tests whether the bit at a given index is set or not.

Syntax:

bitset_name.test(index) 

Parameters: The function accepts only a single mandatory parameter index which specifies the index at which the bit is set or not.

Return Value: The function returns a boolean value. It returns true if the bit at the given index is set else it returns false.

Below programs illustrate the above function:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to illustrate the
// bitset::test() function
// when bitset is a string
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Initialization of bitset
    bitset<4> b1(string("1100"));
    bitset<6> b2(string("010010"));
  
    // Function to check if 2nd index bit
    // is set or not in b1
    if (b1.test(2))
        cout << "Bit at index 2 of 1100 is set\n";
    else
        cout << "Bit at index 2 is not set\n";
  
    // Function to check if 3nd index bit
    // is set or not in b2
    if (b2.test(3))
        cout << "Bit at index 3 of 010010 is set\n";
    else
        cout << "Bit at index 3 of 010010 is not set\n";
  
    return 0;
}

chevron_right


Output:

Bit at index 2 of 1100 is set
Bit at index 3 of 010010 is not set

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to illustrate the
// bitset::test() function
// when the bitset is a number
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Initialization of bitset
    bitset<4> b1(5);
    bitset<6> b2(16);
  
    // Function to check if 2nd index bit
    // is set or not in b1
    if (b1.test(2))
        cout << "Bit at index 2 of 5 is set\n";
    else
        cout << "Bit at index 2 of 5 is not set\n";
  
    // Function to check if 3nd index bit
    // is set or not in b2
    if (b2.test(3))
        cout << "Bit at index 3 of 16 is set\n";
    else
        cout << "Bit at index 3 of 16 is not set\n";
  
    return 0;
}

chevron_right


Output:

Bit at index 2 of 5 is set
Bit at index 3 of 16 is not set


My Personal Notes arrow_drop_up

The function of education is to teach one to think intensively and to think critically

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.