Why the two printf statements are outputting different values?
int main()
{
int n=10;
printf("%d\n",(n&0xAAAAAAAA)>>1 + n&0x55555555 ); //prints 0
printf("%d\n", n&0x55555555 + (n&0xAAAAAAAA)>>1 ); //prints 10
return 0;
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because of the operator precedence.
+is executed earlier than>>.When you change
(n&0xAAAAAAAA)>>1 + n&0x55555555)to
n&0x55555555 + (n&0xAAAAAAAA)>>1)you are actually changing the order in which the operations are executed.
(n&0xAAAAAAAA)>>1 + n&0x55555555can be rewritten as(n&0xAAAAAAAA)>>(1 + n&0x55555555)which is different compared to((n&0xAAAAAAAA)>>1) + n&0x55555555(which is what the second line states)The same goes for the
+and the&operator.So to make the output their outputs similar you need additional parenthesis:
See http://ideone.com/d3mHT