C++ Bitwise Operator Introduction

Introduction

OperatorDescription
~ bitwise complement operator is a unary operator that inverts the bits in its operand, so 1 becomes 0 and 0 becomes 1.
& bitwise AND operator ANDs corresponding bits in its operands. If the corresponding bits are both 1, then the resulting bit is 1, otherwise, it's 0.
^ bitwise exclusive OR operator exclusive-ORs corresponding bits in its operands. If the corresponding bits are different, then the result is 1. If the corresponding bits are the same, the result is 0.
| bitwise OR operator ORs corresponding bits in its operands. If either bit is 1, then the result is 1. If both bits are 0, then the result is 0.
#include <iostream>
#include <iomanip>
using std::setw;// w  w  w  .  j  a  va 2  s .  co m

int main()
{
  unsigned int red {0XFF0000U};             // Color red
  unsigned int white {0XFFFFFFU};           // Color white - RGB all maximum

  std::cout << std::hex                     // Hexadecimal output
            << std::setfill('0');           // Fill character 0

  std::cout << "Try out bitwise AND and OR operators:";
  std::cout << "\nInitial value red = " << setw(8) << red;
  std::cout << "\nComplement   ~red = " << setw(8) << ~red;

  std::cout << "\nInitial value   white = " << setw(8) << white;
  std::cout << "\nComplement     ~white = " << setw(8) << ~white;

  std::cout << "\nBitwise AND red & white = " << setw(8) << (red & white);
  std::cout << "\nBitwise  OR red | white = " << setw(8) << (red | white);

  std::cout << "\n\nNow try successive exclusive OR operations:";
  unsigned int mask {red ^ white};
  std::cout << "\nmask  = red ^ white  = " << setw(8) << mask;
  std::cout << "\n          mask ^ red = " << setw(8) << (mask ^ red);
  std::cout << "\n        mask ^ white = " << setw(8) << (mask ^ white);

  unsigned int flags {0xFF};                // Flags variable
  unsigned int bit1mask {0x1};              // Selects bit 1
  unsigned int bit6mask {0x20};             // Selects bit 6
  unsigned int bit20mask {0x80000};         // Selects bit 20

  std::cout << "\n\nUse masks to select or set a particular flag bit:";
  std::cout << "\nSelect bit 1 from flags   : " << setw(8) << (flags & bit1mask);
  std::cout << "\nSelect bit 6 from flags   : " << setw(8) << (flags & bit6mask);
  std::cout << "\nSwitch off bit 6 in flags : " << setw(8) << (flags &= ~bit6mask);
  std::cout << "\nSwitch on bit 20 in flags : " << setw(8) << (flags |= bit20mask)
            << std::endl;
}



PreviousNext

Related