<< operator in C #

I could not understand this code in C #

 int i=4 int[] s =new int [1<<i]; Console.WriteLine(s.length); 

the output is 16 I don’t know why the conclusion is this?

+4
source share
5 answers
+7
source

From the documentation

If the first operand is int or uint (32-bit number), the number of shifts given by the least five bits of the second operand.

If the first operand is long or oolong (64-bit quantity), the number of shifts specified by six bits of the least significant bit of the second operand.

Note that I <1 and I <33 give the same result, because 1 and 33 have the same low five bits.

This will be the same as 2 ^ (actual value of the lower 5 bits).

So in your case it will be 2 ^ 4 = 16 .

+5
source

I assume you mean i instead of r ...

<<n means "left shift by n * bits". Since you start with 1 = binary 00 ... 00001, if you shift left 4 times, you get binary 00 ... 10000 = 16 (this helps if you are familiar with binary arithmetic - otherwise "calc.exe" has a binary converter )

Each bit moves n places to the left, filling (on the right) with 0s. * = note that n is actually "mod 32" for int , therefore (as an angular case) 1 <33 = 2, not 0, which you can expect.

There is also >> (right shift) that moves to the right, filling in 0 for uint and + ve int s, and 1 for -ve int s.

+3
source

<<- left shift operator

 x << y 

means shift x from left to y bits.

3 is 0011, 3 <1 is 0110, which is 6.

It is usually used to multiply by 2 (left shift is multiplied by 2)

0
source

As already mentioned, <is the left shift operator. In your specific example, the size of the array is defined as power 2. The value 1, shifted to the left by a certain number, will be 1, 2, 4, 8, 16, ...

0
source

All Articles