Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does shifting this bit evalue to 51

I'm currently learning for a C++ examn. One of the questions in the practice examn is:

What is the output of this statement.

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

As I see it. 11 holds the binary equivalent of

1011.

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

0101

Then shifting THAT number one to the left makes it

1010 

Which evaluates to 10.

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

like image 658
Kevin Groen Avatar asked Mar 06 '15 10:03

Kevin Groen


2 Answers

This is due to operator overloading.

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

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

cout << ((11>>1) << 1) <<endl;
// brackets force left shift operator instead of output
like image 110
TartanLlama Avatar answered Oct 21 '22 05:10

TartanLlama


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

becomes

cout << 5 << 1 <<endl;

The streaming meaning of << takes precedence over the shifting meaning. Therefore it prints a 5 followed by a 1.

like image 21
Neil Kirk Avatar answered Oct 21 '22 03:10

Neil Kirk