C# - Bitwise AND, OR, XOR Example

Here, we are going to learn about the bitwise operations and demonstrate the example of bitwise operations in C#.
Submitted by Nidhi, on October 09, 2020 [Last updated : March 17, 2023]

Here, we will demonstrate Bitwise AND, Bitwise OR, and Bitwise XOR operations.

C# program to demonstrate the bitwise operations (AND, OR, XOR)

The source code to demonstrate the bitwise operations is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# - Bitwise AND, OR, XOR Example.

using System;

class Bitwise
{
    public static void Main()
    {
        byte num1   = 10;
        byte num2   = 2;
        byte result = 0;

        result  =  (byte)(num1 & num2);
        Console.WriteLine("{0} & {1} = {2}",num1,num2, result);

        result = (byte)(num1 | num2);
        Console.WriteLine("{0} | {1} = {2}", num1, num2, result);

        result = (byte)(num1 ^ num2);
        Console.WriteLine("{0} ^ {1} = {2}", num1, num2, result);
    }
}

Output

10 & 2 = 2
10 | 2 = 10
10 ^ 2 = 8
Press any key to continue . . .

Explanation

Here, we created a class Bitwise that contains the Main() method. Here, we declared three variables of byte type that are initialized with 10, 2, and 0 respectively.

result  =  (byte)(num1 & num2);
Console.WriteLine("{0} & {1} = {2}",num1,num2, result);

result = (byte)(num1 | num2);
Console.WriteLine("{0} | {1} = {2}", num1, num2, result);

In the above code, we performed the bitwise AND, bitwise OR, and bitwise XOR operations and printed the result on the console screen.

C# Basic Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




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

© https://www.includehelp.com some rights reserved.