C++ Standard Library C++ STL Library

C++ <bitset> - test() Function



The C++ bitset::test function is used to check if the bit at specified position is set or not. It returns true if the bit at specified position is set, else returns false.

Syntax

bool test (size_t pos) const;
bool test (size_t pos) const;

Parameters

pos Specify position of the bit whose value is retrieved.

Return Value

true if the bit at specified position is set, false otherwise.

Exception

Throws out_of_range, if specified position is not a valid bit position.

Example:

The example below shows the usage of bitset::test function.

#include <iostream>
#include <bitset>
using namespace std;
 
int main (){
  bitset<4> bset("1100");
  
  cout<<boolalpha;
  cout<<"Is b[0] set: "<<bset.test(0)<<"\n";
  cout<<"Is b[1] set: "<<bset.test(1)<<"\n";
  cout<<"Is b[2] set: "<<bset.test(2)<<"\n";
  cout<<"Is b[3] set: "<<bset.test(3)<<"\n";

  return 0;
}

The output of the above code will be:

Is b[0] set: false
Is b[1] set: false
Is b[2] set: true
Is b[3] set: true

❮ C++ <bitset> Library