·  C# – Syntax – Operators – Bitwise

 

- Info:

  - This tutorial shows how to use Conditional Operators in C#.: & | ^ ~ << >>.

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

 

- Example:

  - Create C# Console Application Test.cs.

 

    Test.cs

    using System;

   

    class Test {

   

      static void Main(string[] args) {

   

        //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.

        Console.WriteLine(and_op     );  //  18 = 10010

        Console.WriteLine(and_op     );  //  18 = 10010

        Console.WriteLine(or_op      );  //  27 = 11011

        Console.WriteLine(xor_op     );  //   9 = 01001

        Console.WriteLine(invert     );  // -28 = 111111100100

        Console.WriteLine(shiftLeft  );  // 216 = 11011000

        Console.WriteLine(shiftRight );  //   6 = 110

   

      }

   

    }