0

The output of the following code is '8'. How?

int x=2; Console.WriteLine(x<<2);

2nd Oct 2017, 8:24 PM
Mr. Pool
Mr. Pool - avatar
5 Respuestas
+ 12
It is moved 2 bits to the left, bitwise. Consider 2 as binary: 0010 If you move the bits by 2 spaces to the left (what this operation does), you get: 1000 Which in decimal is 8 :)
2nd Oct 2017, 8:28 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 6
In this context, << is a binary operation, also known as a "shift". The shift direction is "left", 2 times. First, represent the base-10 number 2 in binary (base 2). This one has two leading zeros because it makes my examples line up: 0010 = 0*2³ + 0*2² + 1*2¹ + 0*2° = 0 + 0 + 2 + 0 = 2 Now shift the entire thing left two spots, filling in zeros at the right (and dropping the extra leading zeroes for simplicity): 1000 = 1*2³ + 0*2² + 0*2¹ + 0*2° = 8 + 0 + 0 + 0 = 8 Another way to look at shifting is that each left shift multiplies the value by 2: 0011 = 3 ( 2+1 ) 0110 = 6 ( 4+2 ) 1100 = 12 (8+4 ) Two shifts is double, then double again.
2nd Oct 2017, 8:37 PM
Kirk Schafer
Kirk Schafer - avatar
+ 5
Left bit shift is pretty simple to understand once you know a little binary. The shift amount is equal to taking the number and multiplying it by 2 the amount of shift that is taking place. In other words with: 5 << 4 the result will be equal to 5 * 2 * 2 *2 * 2 in C#: Console.WriteLine(42<<5); is equivalent to: int num = 42; int shift = 5; for(int i = 0; i < shift; ++i) { num*=2; }
2nd Oct 2017, 9:19 PM
ChaoticDawg
ChaoticDawg - avatar
+ 3
2 in bits is 0010 we shift this number to the left by 2 bits, so we get 1000 (in bits) When we covert it to decimal you get 8 ^^
2nd Oct 2017, 8:28 PM
Jakub Stasiak
Jakub Stasiak - avatar
0
Thanks bro...
2nd Oct 2017, 8:33 PM
Mr. Pool
Mr. Pool - avatar