Demonstrate bitset : Bitset « Data Structure « C++






Demonstrate bitset

Demonstrate bitset

#include <iostream>
#include <bitset>
using namespace std;

int main()
{
  bitset<16> bitsetObject(32);

  cout << "Bits:";
  cout << bitsetObject; 
  cout << endl;

  bitsetObject[0] = 1;
  bitsetObject[2] = 0;
  bitsetObject[10] = 1;
  bitsetObject[12] = 1;

  cout << "Bits:";
  cout << bitsetObject;
  cout << endl;

  
  bitsetObject <<= 2;   // rotate bits
  cout << "Bits rotate: ";
  cout << bitsetObject;
  cout << endl;

  
  bitsetObject.flip(); // flip bits
  cout << "After flipping bits:    ";
  cout << bitsetObject;
  cout << endl;

  if(bitsetObject.any()) 
     cout << "bitsetObject has at least 1 bit set.\n";
  
  cout << "bitsetObject has " << bitsetObject.count();
  cout << " bits set.\n";

  // test bits different three ways
  if(bitsetObject[0] == 1)
    cout << "bit 0 is on\n";
  if(bitsetObject.test(1))
    cout << "bit 1 is on\n";

  cout << "Add 11 to bit 0: " << bitsetObject[0] + 11 << endl;   // can add bits to integers

  return 0;
}

           
       








Related examples in the same category