C# program to demonstrate example of bitwise operators

C# example for bitwise operators: Here, we are writing a C# program to demonstrate example of bitwise operators.
Submitted by IncludeHelp, on April 06, 2019

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
```

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
}
}
}
```

Output

```a & b  : 2
a | b  : 11
a ^ b  : 9
~a     : -11
a << b : 40
a >> b : 2
```

What's New (MCQs)

Top Interview Coding Problems/Challenges!

IncludeHelp's Blogs

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates