-3
var x = 2;
var y=x+2<<2;
Console.WriteLine(y);
output = 16

my doubt is that how 16 is come.i know about bitwise shift left operator.what kind of operation is done.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

2 Answers2

2

Pay attention to operator precedence. 2 + 2 << 2 is not 2 + (2 << 2).

Luaan
  • 62,244
  • 7
  • 97
  • 116
1

its same as below :-

x + 2 = 4;

4 << 2 ////it means 16 if you perform bitwise on this.

Desciption to understand Let shift operation :-

Shifts bits to the left. The number to the left of the operator is shifted the number of places specified by the number to the right. Each shift to the left doubles the number, therefore each left shift multiplies the original number by 2. Use the left shift for fast multiplication or to pack a group of numbers together into one larger number. Left shifting only works with integers or numbers which automatically convert to an integer such at byte and char.

so in your case lets say presentation for 4 is 100 and it would be shifted by 2 so it becomes 10000 which is presentation of 16 :-

for 4 :- 100
left shift by 2 so,
10000 ////Which is 16
Neel
  • 11,625
  • 3
  • 43
  • 61