• Home
• C#
• PHP
• Blog
• Lesson 3.4

# C# Bitwise Operator – With Programming Examples

Objective

What is Bitwise operator in C#?
What is the symbol of Bitwise Operator?
How to use Bitwise Operator in program?

## C# Bitwise Operator – With Programming Examples

The AND (&), EXCLUSIVE OR(^), INCLUSIVE OR (|) is simply called as bitwise operator. These operators compare two operands at bit level and returned results according their rules.

### Bitwise Operator Symbol

Here we assume that the variable num1 contains 45 and num2 contains 55. Num3 is used for storing result.

Binary Value of 45 is : 0010 1101
Binary Value of 55 is : 0011 0111

### Bitwise AND (&) Operator

The bitwise AND (&) operator compares each bit of first variable to each bit of second variable. If both value are 1 then it set bit value to 1 otherwise it set 0.

### Example:

num3 = num1 & num2;

Let’s understand it as follow:

Num1 = 0010 1101
Num2 = 0011 0111
-------------------------------------
Num3 = 0010 0101

So the num3 holds the value 37 which is equivalent to binary number 0010 0101

### Bitwise EXCLUSIVE OR (^) or XOR

The bitwise Exclusive OR (^) or XOR Operator compares each bit of first variable to each bit of second variables. If the one variable bit is 0 and another variable bit is 1 then it stores bit value 1 in results otherwise it stores 0.

### Example:

num3 = num1 ^ num2;

Let’s understand it as follow:

Num1= 00101101
Num2= 00110111
-------------------------------------
Num3= 00011010

So, the num3 holds the value 26 which is equivalent to binary number 0001 1010

### Bitwise Inclusive OR (|)

The bitwise-inclusive-OR operator compares each bit of its first operand to the corresponding bit of its second operand. If either bit is 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.

### Example:

num3 = num1 | num2;

Let’s understand it as follow:

Num1= 0010 1101
Num2= 0011 0111
-------------------------------------
Num3= 00111111

So, the num3 holds the value 63 which is equivalent to binary number 0011 1111

### Programming Example

```using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace bitwise_operators
{
class Program
{
static void Main(string[] args)
{
int num1, num2, num3;
num1 = 45;
num2 = 55;

//Using Bitwise AND(&) Operator
num3 = num1 & num2;
Console.WriteLine(num3);

//Using Bitwise Exclusive OR(^) Operator
num3 = num1 ^ num2;
Console.WriteLine(num3);

//Using Bitwise Inclusive OR(|) Operator
num3 = num1 | num2;
Console.WriteLine(num3);

}
}
}

```

37
26
63
__

## Summary

In this chapter you have learned what bitwise operator is in C # and how to use it in programming. In the next chapter you will learn about Assignment Operators in C#.  