Friday, 17 August 2018

C#: Shift Operators

Bit Wise Left Shift(<<)
Left shift operator shifts all the bits to one bit left, i.e, it simply doubles the value.

Syntax:
    variable << n

    left shift the variable by 'n' number of times.

    Variable << n is equals to variable = variable * 2 power n

        int var = 2;
        var << 1 = 2 * 2 power 1 = 4
        var << 2 = 2 * 2 power 2 = 8
        var << 9 = 2 * 2 power 9 = 1024

Program.cs
using System;

class Program
{
    static void Main(string[] args)
    {
        byte byteVar = 7;

        Console.WriteLine("Value of Byte variable is " + byteVar);
        Console.WriteLine("After shifting 1 bit left " + (byteVar << 1));
        Console.WriteLine("After shifting 2 bits left " + (byteVar << 2));
        Console.WriteLine("After shifting 3 bits left " + (byteVar << 3));
        Console.WriteLine("After shifting 4 bits left " + (byteVar << 4));
        Console.WriteLine("After shifting 5 bits left " + (byteVar << 5));
        Console.WriteLine("After shifting 6 bits left " + (byteVar << 6));
        Console.WriteLine("Value of Byte variable is " + byteVar);
    }
}

Output

Value of Byte variable is 7
After shifting 1 bit left 14
After shifting 2 bits left 28
After shifting 3 bits left 56
After shifting 4 bits left 112
After shifting 5 bits left 224
After shifting 6 bits left 448
Value of Byte variable is 7



Bit Wise Right Shift(>>)
Right shift operator shifts all the bits to one bit right, i.e, it simply half (divide by 2) the value

   Syntax:
   variable >> n
      right shift the variable by 'n' number of times.

   Variable >> n is equals to variable = variable / 2 power n

   int var = 128;
   var >> 1 = 128 / (2 power 1) = 64
   var >> 2 = 128 / (2 power 2) = 32

Program.cs

using System;

class Program
{
    static void Main(string[] args)
    {
        int intVar = 128;

        Console.WriteLine("Value of int variable is " + intVar);
        Console.WriteLine("After shifting 1 bit Right " + (intVar >> 1));
        Console.WriteLine("After shifting 2 bits Right " + (intVar >> 2));
        Console.WriteLine("After shifting 3 bits Right " + (intVar >> 3));
        Console.WriteLine("After shifting 4 bits Right " + (intVar >> 4));
        Console.WriteLine("After shifting 5 bits Right " + (intVar >> 5));
        Console.WriteLine("After shifting 6 bits Right " + (intVar >> 6));
        Console.WriteLine("After shifting 6 bits Right " + (intVar >> 7));
        Console.WriteLine("Value of int variable is " + intVar);
    }
}

Output

Value of int variable is 128
After shifting 1 bit Right 64
After shifting 2 bits Right 32
After shifting 3 bits Right 16
After shifting 4 bits Right 8
After shifting 5 bits Right 4
After shifting 6 bits Right 2
After shifting 6 bits Right 1
Value of int variable is 128





Previous                                                 Next                                                 Home

No comments:

Post a Comment