0
what is the output of this? cout<<(1< <1) & how? please explain....
3 Respuestas
+ 2
Mathematically, bitwise left shift ('<<' operator, as previously stated, shift bits of the left hand value by nth position specified at right hand value) is equivalent to multiply the left hand value by 2 raised to the power of the right hand value (because each one digit left shift of number in base 2 multiply it by 2, as one digit left shift of number in base 10 multiply it by 10):
a << b
... is equivalent to:
a * std::pow(2,b)
... but with more efficiency (quickest).
Obviously, you need to include <cmath> header to be able to use (call) the pow() function ^^
So (with 'using namespace std;'):
1 << 1 == 1 * pow(2,1) == 1 * 2 == 2
+ 1
It's cout << ( 1 << 1 )
In the machine the 1 is represented as 0000 0001.
And the operation << moves all bits on the left by how places you want
1 -> 0000 0001
1 << 1 = [ 1 shift all by one position ]
result -> 0000 0010
Which is 2 for the humans
0
answer is 2
This is called left shift
this is what happened there :-
1 = 0000 0001 (base 2 form of 1)
so when you do 1<<1, entire base 2 digits are shifted left once and 0 is added to the end
so it becomes,
1 << 1 = 0000 0010
left part is converted into base 2 form, while the right part specifies number of bits to shift and '<<' or '>>' specifies the direction of shift
eg: 3 << 2
base 2 form of 3 = 0000 0011
no. of bits to shift = 2
direction of shift = left
base 2 form after shift = 0000 1100
numerical form after (base 10) = 12
numerical form of the number after shift was displayed when you ran the program which in this case is 12