·  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.c.

 

    Test.c

    #include <stdio.h>

   

    int main() {

   

      /* BITWISE OPERATORS.-------------------------------------------------------------------------- */

      int left        = 27;            /* 11011b */

      int right       = 18;            /* 10010  */

   

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

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

      int xor         =  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. */

   

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

      printf("%i\n",or        ); /*  27=11011        */

      printf("%i\n",xor       ); /*   9=01001        */

      printf("%i\n",invert    ); /* -28=111111100100 */

      printf("%i\n",shiftLeft ); /* 216=11011000     */

      printf("%i\n",shiftRight); /*   6=110          */

   

      return 1;

   

    }