4

i couldn't understand this code in c#

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

the ouput is 16 i don't know why the output like that?

Can Berk Güder
  • 109,922
  • 25
  • 130
  • 137
khtaby
  • 51
  • 2

5 Answers5

7

bit shift operator

Dustin Getz
  • 21,282
  • 15
  • 82
  • 131
5

From documentation

If first operand is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of second operand.

If first operand is a long or ulong (64-bit quantity), the shift count is given by the low-order six bits of second operand.

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

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

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

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
3

I'm assuming you mean i in place of r...

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

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

There is also >> (right shift), which moves for the right, filling with 0 for uints and +ve ints, and 1 for -ve ints.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

<< is the left shift operator

x << y

means shift x to the left by y bits.

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

It's usually used to multiply by 2 (shifting to the left is multiplying by 2)

Soufiane Hassou
  • 17,257
  • 2
  • 39
  • 75
0

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

Mark Wilkins
  • 40,729
  • 5
  • 57
  • 110