C# Illustrate Bitwise Operations

Operations can be performed on a bit level using bitwise operators.

Bitwise operations are contrasted by byte-level operations which characterize the bitwise operators’ logical counterparts, the AND, OR and NOT operators. Instead of performing on individual bits, byte-level operators perform on strings of eight bits (known as bytes) at a time. The reason for this is that a byte is normally the smallest unit of addressable memory (i.e. data with a unique memory address.)

This applies to bitwise operators as well, which means that even though they operate on only one bit at a time they cannot accept anything smaller than a byte as their input. (wiki)

 

using System;

class Bitwise
{
    byte b1, b2;
    int x;
    long y;

    Bitwise()
    {
        b1 = 10;
        b2 = 5;
        x = 32;
        y = 20;
    }

    public static void Main()
    {
        Bitwise bit = new Bitwise();

        byte p = (byte)(bit.b1 & bit.b2);
        byte q = (byte)(bit.b1 | bit.b2);
        byte r = (byte)(bit.b1 ^ bit.b2);
        int z = (int)(bit.x & bit.y);

        Console.WriteLine("b1={0}, b2={1}, x={2}, y={3}\n", bit.b1, bit.b2, bit.x, bit.y);
        Console.WriteLine("b1 & b2={0}: ", p);
        Console.WriteLine("b1 | b2={0}: ", q);
        Console.WriteLine("b1 ^ b2={0}: ", r);
        Console.WriteLine("x & y = {0}: ", z);

        Console.ReadLine();
    }
}

 

Output