0

//((Hello everybody! i am C# beginner can any one tell me the function of left and right shift operator and their working way w.r.t the following program. I read it somewhere but confuse. thanks ))

using System;
class clc
{
    public static void Main() // the Main method
    {
        int x = 7, y = 2, z, r;
        z = x << y ; //left shift operator
        r = x >> y; // right shift operator
        Console.WriteLine("\n z={3}\tr={4} ",z,r);

    }
}
Irfan Ul Haq
  • 1,065
  • 1
  • 11
  • 19
  • 1
    Did you take a look at [C# Operators](http://msdn.microsoft.com/en-gb/library/6a71f45d.aspx) on MSDN? What there did you not understand? – Oded Mar 03 '13 at 17:58

1 Answers1

1

To understand the shift operations you must understand binary numbers.

Let's take your example for left shift:

z = 7 << 2;

32 bit integer 7 is 0000 0000 0000 0000 0000 0000 0000 0111 in binary. You must move the bits to the left beginning from the right. The bits that are shifted out of either end are discarded.

Shifting it by 1 will result 0000 0000 0000 0000 0000 0000 0000 1110

Shifting it by 1 one more time will result 0000 0000 0000 0000 0000 0000 0001 1100 which is 28 in integer representation.

Read this good wikipedia article Binary number

VladL
  • 12,769
  • 10
  • 63
  • 83