0
Why is the output 2?
cout << (1<<1) ;
2 Antworten
+ 9
Its because you are sifting it to the left by 1 (multiplying by 2)
Let's have a look at the binary of one
1 = 0001
Now shifting it left by 1 means all the bits will move 1 step to left (0 will be add on the rightmost)
so it will be like this
0001 << 1 = 0010
0010 is the binary of 2
if we do it again by 1
0010 << 1 = 0100
0100 is the binary of 4
so what's happening is the bits are shifted to left by n where n = 1.
Similary, we shift 1 by 2
0001 << 2
In this case each bit will be shifted to left by 2 and 0's will be added to the rightmost sides.
0001 << 2 = 0100 = 4
+ 13
This is left shift operator. It shifts the binary equivalent of first operand by n bit (n is the 2nd operand).
Binary equivalent of 1 is: 1
After shifting 1 bit left, it becomes: 10 = decimal 2
Reference: https://www.geeksforgeeks.org/left-shift-right-shift-operators-c-cpp/