Q:

C# program to demonstrate example of bitwise operators

belongs to collection: C# Basic Programs | basics

0

Bitwise operators are used to perform calculations on the bits.

Here is the list of bitwise operators,

  1. "&" (Bitwise AND) – returns 1 (sets bit), if both bits are set
  2. "|" (Bitwise OR) – returns 1 (sets bit), if any or all bits are set
  3. "^" (Bitwise XOR) – returns 1 (sets bit), if only one bit is set (not both bits are set)
  4. "~" (Bitwise NOT) – returns one’s compliment of the operand, it’s a unary operator
  5. "<<" (Bitwise Left Shift) – moves the number of bits to the left
  6. ">>" (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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | basics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# | Find the addition of two integer numbers... >>
<< C# program to demonstrate example of relational op...