·  C++ – Syntax – Operators – Bitwise

 

- Info:

  - Bitwise Operators operate on individual bits of int and long values: & | ^ ~ << >>.

  - If an operand is shorter than an int, it is promoted to int before doing the operations.

 

- Example:

  - Create C++ Console Application Test.cpp.

 

    Test.cpp

    #include <stdio.h>

    #include <iostream>

    using namespace std;

   

    int main() {

   

      //TEST VARIABLES.

      int left        = 27;            // 11011b

      int right       = 18;            // 10010

   

      //BITWISE OPERATORS.

      int and_op      =  left & right; // 10010.    1 if both   bits are 1.

      int or_op       =  left | right; // 11011.    1 if either bit  is  1.

      int xor_op      =  left ^ right; // 01001.    1 if        bits are different.

      int invert      = ~left;         // 00100.    Invert bits.

      int shiftLeft   =  left <<  3;   // 11011000. Shift bits to the left  by 3. Fill with 0.

      int shiftRight  =  left >>  2;   // 110.      Shift bits to the right by 2. Fill with 0.

   

      //DISPLAY RESULTS.

      printf("%i\n",and_op);           //  18 = 10010

      cout << and_op     << endl;      //  18 = 10010

      cout << or_op      << endl;      //  27 = 11011

      cout << xor_op     << endl;      //   9 = 01001

      cout << invert     << endl;      // -28 = 111111100100

      cout << shiftLeft  << endl;      // 216 = 11011000

      cout << shiftRight << endl;      //   6 = 110

   

      return 1;

   

    }