Home » 
        .Net » 
        C# Programs
    
    
    C# Bitwise Operators Example
    
    
    
	
    
        C# example for bitwise operators: Here, we are writing a C# program to demonstrate example of bitwise operators.
        
            By IncludeHelp Last updated : April 15, 2023
        
    
    Bitwise Operators
    Bitwise operators are used to perform calculations on the bits.
    Here is the list of bitwise operators,
    
        - "&" (Bitwise AND) – returns 1 (sets bit), if both bits are set
- "|" (Bitwise OR) – returns 1 (sets bit), if any or all bits are set
- "^" (Bitwise XOR) – returns 1 (sets bit), if only one bit is set (not both bits are set)
- "~" (Bitwise NOT) – returns one’s compliment of the operand, it’s a unary operator
- "<<" (Bitwise Left Shift) – moves the number of bits to the left 
- ">>" (Bitwise Right Shift) – moves the number of bits to the right
Syntax
Operand1 & Operand2
Operand1 | Operand2
Operand1 ^ Operand2
~Operand
Operand1 << Operand2
Operand1 >> Operand2
Example
Input:
int a = 10;
int b = 3;
    
//operations
a & b   = 2
a | b   = 11
a ^ b   = 9
~a      = -11
a << 2  = 40
a >> 2  = 2
    
C# code to demonstrate example of bitwise operators
// C# program to demonstrate example of 
// bitwise operators
using System;
using System.IO;
using System.Text;
namespace IncludeHelp {
  class Test {
    // Main Method 
    static void Main(string[] args) {
      int a = 10;
      int b = 3;
      int result = 0;
      result = a & b; //1010 & 0011 = 0010 = 3
      Console.WriteLine("a & b  : {0}", result);
      result = a | b; //1010 | 0011 = 1011 = 11
      Console.WriteLine("a | b  : {0}", result);
      result = a ^ b; //1010 ^ 0011 = 1001
      Console.WriteLine("a ^ b  : {0}", result);
      result = ~a; //ones compliment of 10
      Console.WriteLine("~a     : {0}", result);
      result = a << 2; //1010<<2 = 101000 = 40
      Console.WriteLine("a << b : {0}", result);
      result = a >> 2; //1010>>2 = 0010 = 2
      Console.WriteLine("a >> b : {0}", result);
      //hit ENTER to exit the program
      Console.ReadLine();
    }
  }
}
Output
a & b  : 2
a | b  : 11
a ^ b  : 9
~a     : -11
a << b : 40
a >> b : 2
	C# Basic Programs »
	
	
    
    
    
    
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement