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?
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?
Hey, khtabby! Welcome to Stack Overflow!
It doesn't look like your code copied as you intended. You should probably edit. While you're editing, if you put four spaces before each line, it will format it like code.
int i = 4;
int[] s = new int [1<
<< 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)
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 uint
s and +ve int
s, and 1
for -ve int
s.
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, ...
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.