cppreference.com -> C++ Bitsets -> Details

C++ Bitsets


Constructors

Syntax:

  bitset();
  bitset( unsigned long val );

Bitsets can either be constructed with no arguments or with an unsigned long number val that will be converted into binary and inserted into the bitset. When creating bitsets, the number given in the place of the template determines how long the bitset is.

For example, the following code creates two bitsets and displays them:

  // create a bitset that is 8 bits long
  bitset<8> bs;

  // display that bitset
  for( int i = (int) bs.size(); i >= 0; i-- ) {
    cout << bs[i] << " ";
  }
  cout << endl;

  // create a bitset out of a number
  bitset<8> bs2( (long) 131 );

  // display that bitset, too
  for( int i = (int) bs2.size(); i >= 0; i-- ) {
    cout << bs2[i] << " ";
  }
  cout << endl;


Operators

Syntax:

  !=, ==, &=, ^=, |=, ~, <<=, >>=, []

These operators all work with bitsets. They can be described as follows:

For example, the following code creates a bitset and shifts it to the left 4 places:

  // create a bitset out of a number
  bitset<8> bs2( (long) 131 );

  cout << "bs2 is " << bs2 << endl;

  // shift the bitset to the left by 4 digits
  bs2 <<= 4;

  cout << "now bs2 is " << bs2 << endl;

When the above code is run, it displays:

  bs2 is 10000011
  now bs2 is 00110000

any

Syntax:

  bool any();

The any() function returns true if any bit of the bitset is 1, otherwise, it returns false.


count

Syntax:

  size_type count();

The function count() returns the number of bits that are set to 1 in the bitset.


flip

Syntax:

  bitset &flip();
  bitset &flip( size_t pos );

The flip() function inverts all of the bits in the bitset, and returns the bitset. If pos is specified, only the bit at position pos is flipped.

Related topics:
~ operator

none

Syntax:

  bool none();

The none() function only returns true if none of the bits in the bitset are set to 1.


reset

Syntax:

  bitset &reset();
  bitset &reset( size_t pos );

The reset() fucntion clears all of the bits in the bitset, and returns the bitset. If pos is specified, then only the bit at position pos is cleared.


set

Syntax:

  bitset &set();
  bitset &set( size_t pos, int val=1 );

The set() fucntion sets all of the bits in the bitset, and returns the bitset. If pos is specified, then only the bit at position pos is set.


size

Syntax:

  size_t size();

The size() function returns the number of bits that the bitset can hold.


test

Syntax:

  bool test( size_t pos );

The function test() returns the value of the bit at position pos.


to_string

Syntax:

  string to_string();

The to_string() function returns a string representation of the bitset.


to_ulong

Syntax:

  unsigned long to_ulong();

The function to_ulong() returns the bitset, converted into an unsigned long integer.