Logical Bitwise Operators - CSharp Language Basics

CSharp examples for Language Basics:Operator

Introduction

Operator Description
| Logical OR bitwise operator
& Logical AND bitwise operator
^ Logical XOR bitwise operator

The Logical OR Bitwise Operator

When combining two values with the logical OR bitwise operator ( |), you get the following results:

  • If both bits are 0, the result is 0.
  • If either or both bits are 1, the result is 1.

Combining 2 byte values results in the following:

Value 1:   00001111
Value 2:   11001100
           --------

Result

The Logical AND Bitwise Operator

When combining two values with the logical AND bitwise operator (&), you get the following result:

  • If both bits are 1, the result is 1.
  • If either bit is 0, the result is 0.

Combining 2 byte values results in the following:

Value 1:   00001111
Value 2:   11001100
           --------

Result

The Logical XOR Operator

When combining two values with the logical XOR bitwise operator (^), you get the following result:

  • If both bits are the same, the result is 0.
  • If 1 bit is 0 and the other is 1, the result is 1.

Combining 2 byte values results in the following:

Value 1:    00001111
Value 2:    11001100
            --------

Result

Demo Code

class MainClass//w  ww  . j  a v  a2  s  .  c  o  m
{
   static void Main()
   {
      int ValOne = 1;
      int ValZero = 0;
      int NewVal;
      // Bitwise NOT Operator
      NewVal = ValZero ^ ValZero;
      System.Console.WriteLine("\nThe NOT Operator: \n  0 ^ 0 = {0}", NewVal);
      NewVal = ValZero ^ ValOne;
      System.Console.WriteLine("  0 ^ 1 = {0}", NewVal);
      NewVal = ValOne ^ ValZero;
      System.Console.WriteLine("  1 ^ 0 = {0}", NewVal);
      NewVal = ValOne ^ ValOne;
      System.Console.WriteLine("  1 ^ 1 = {0}", NewVal);
      // Bitwise AND Operator
      NewVal = ValZero & ValZero;
      System.Console.WriteLine("\nThe AND Operator: \n  0 & 0 = {0}", NewVal);
      NewVal = ValZero & ValOne;
      System.Console.WriteLine("  0 & 1 = {0}", NewVal);
      NewVal = ValOne & ValZero;
      System.Console.WriteLine("  1 & 0 = {0}", NewVal);
      NewVal = ValOne & ValOne;
      System.Console.WriteLine("  1 & 1 = {0}", NewVal);
      // Bitwise OR Operator
      NewVal = ValZero | ValZero;
      System.Console.WriteLine("\nThe OR Operator: \n  0 | 0 = {0}", NewVal);
      NewVal = ValZero | ValOne;
      System.Console.WriteLine("  0 | 1 = {0}", NewVal);
      NewVal = ValOne | ValZero;
      System.Console.WriteLine("  1 | 0 = {0}", NewVal);
      NewVal = ValOne | ValOne;
      System.Console.WriteLine("  1 | 1 = {0}", NewVal);
   }
}

Result


Related Tutorials