Why transfer this bit to 51

I am currently participating in the C ++ exam. One of the issues in practice is:

What is the result of this statement.

cout <<(11>>1)<<1<<endl; 

As I can see. 11 contains the binary equivalent

 1011. 

Shifting this binary number from 1 bit to the right makes it:

 0101 

Then shifting this number one left makes it

 1010 

Which is rated to 10.

However, by running the same statement in my compiler, it says that the number is estimated to 51. Can someone explain this to me?

+6
source share
3 answers

This is due to operator overload.

 cout <<(11>>1)<<1<<endl; // ^ output operator // ^ right shift // ^ output operator 

If you changed the code to this, then your answer would be correct:

 cout << ((11>>1) << 1) <<endl; // brackets force left shift operator instead of output 
+13
source

cout << (11>>1) << 1 << endl;

becomes

cout << 5 << 1 <<endl;

The streaming value << takes precedence over the offset value. So he prints 5 followed by 1.

+6
source
 int a = (11>>1); int b = 1; cout << a << b; 

Clear?

+4
source

Source: https://habr.com/ru/post/983416/


All Articles