Hello ppl,

I have recently started C# and while going through initial pages of bitwise operators 1 doubt came into mind.

v know dat int is of 32 bits in C#. Suppose i take a number and assign some value to it and then after left shifting it by 32,the number doesn't get changed. If i do left shift 33 times the number gets multiplied by 2. However Left shifting by 31 and then left shifting it by 1 after that will make the number 0.

What is actually happening....plz help

to my surprise same 16 left shifting in C(as int is 16 bits in C) will make the number 0 and by left shifting 17 will keep the number to 0.

My Code Snippet for the same is:

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int num=7;

            num = num << 32;

            Console.WriteLine("Left shift by 32->"+num);

            num = 7;

            num = num << 33;

            Console.WriteLine("Left shift by 33->"+num);

            num = 7;

            num = num << 31;
            num = num << 1;

            Console.WriteLine("Left shift 31 first den left shift once again->" + num);

            Console.ReadKey();
        }
    }
}

Output:

7
14
0

* When the type of x is int or uint, the shift count is given by the low-order five bits of count. In other words, the shift count is computed from count & 0x1F.
* When the type of x is long or ulong, the shift count is given by the low-order six bits of count. In other words, the shift count is computed from count & 0x3F.

So in your first example, 32 = 0x0010 0000 and is anded with 0x0001 1111
0x0010 0000
0x0001 1111
-----------
0x0000 0000

So no shift occurs.
33 has a bit in the first position so it's the same as shifting 1

You can consider the shift number to be the same as x mod 32 (x % 32).

commented: Good knowledge +0

Thank u so much sir,

I got the concept......No matter how big the number is......i need 2 divide it by 32 in case of int 2 get the required no. of shifting.....

But, Sir i have executed the same program in C using Turbo C compiler....In that it was not following remainder after dividing by 16 case......


please throw lights on dat concept of execution also.....

Turbo C is a different language with a different specification. The C# language specification requires that the << and >> operate as above. I don't have the C language specification so I can't tell you how they are supposed to operate.

Ok sir, I will try to search it and if i come to know about it...I will definitely post here

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.