0

Cout << (1<<2) [C++]

so i met this question on the challenge thing, and i dont quite understand how this thing could produce 4. Can someone please explain to me how does this works? thanks in advance.

5th Jul 2018, 12:42 PM
Samuel Auditama
Samuel Auditama - avatar
2 Answers
+ 1
<< , >> are bitwise lest shift and right shift operators respectively. x << 2 shifts the bits of numbers towards left by 2 example : x = 10 ==> (1010) in binary 1010 ← 101000 lest shift by 2 position (101000) in binary = 40 in decimal. so x<<2 => 40 (if x= 10) 1 position left shift is equivalent to number multiply by 2( until bits doesn't overflow) x>>2 means shift right by two position. Example : x = 10 => 1010 1010 → 10 //shifted right by 2 position 10 in binary => 2 in decimal so x>>2 = 2 (if x= 10) 1 position right shift is equivalent to number's division by 2. EDIT: so 1<<2 1 in decimal = 1 in binary 1 ← 100 //left shift by 2 (100) in binary => 4 in decimal 1<<2 => 4
5th Jul 2018, 1:05 PM
Nikhil Dhama
Nikhil Dhama - avatar
+ 1
Hello! It's shift operator, learn more in docs. https://msdn.microsoft.com/en-us/library/336xbhcz.aspx
5th Jul 2018, 12:55 PM
dev.Y
dev.Y - avatar