C++ Standard Library C++ STL Library

C++ <bitset> - operator<< Function



The C++ <bitset> operator<< function is used to insert bitset rhs to the character stream os.

Syntax

template<class charT, class traits, size_t N>
  basic_ostream<charT, traits>&
    operator<< (basic_ostream<charT,traits>& os, const bitset<N>& rhs);
template<class charT, class traits, size_t N>
  basic_ostream<charT, traits>&
    operator<< (basic_ostream<charT, traits>& os, const bitset<N>& rhs);

Parameters

os The basic_ostream object from which the bitset object is inserted.
rhs Specify right-hand side bitset object.

Return Value

Returns the character stream os.

Exception

In case of exception, all object remains in valid state.

Example:

The example below shows the usage of operator<< function.

#include <iostream>
#include <bitset>
#include <sstream>
using namespace std;
 
int main (){
  string s = "111000";
  istringstream stream(s);
  bitset<2> bset1;
  bitset<4> bset2;

  //extracting first 2 bits into bset1
  stream >> bset1;
  cout<<"bset1 = "<<bset1;

  //extracting next 4 bits into bset2
  stream >> bset2;
  cout<<"\nbset2 = "<<bset2;

  return 0;
}

The output of the above code will be:

bset1 = 11
bset2 = 1000

❮ C++ <bitset> Library