Bitset Operators

C/C++ Reference

Bitset Operators
Syntax:
  #include <bitset>
  !=, ==, &=, ^=, |=, ~, <<=, >>=, []

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

  • != returns true if the two bitsets are not equal.
  • == returns true if the two bitsets are equal.
  • &= performs the AND operation on the two bitsets.
  • ^= performs the XOR operation on the two bitsets.
  • |= performs the OR operation on the two bitsets.
  • ~ reverses the bitset (same as calling flip())
  • <<= shifts the bitset to the left
  • >>= shifts the bitset to the right
  • [x] returns a reference to the xth bit in the bitset.

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