Strange behaviour of bit shift
bit-manipulation, c
Solution
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&0x55555555` can 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:
int main()
{
int n=10;
printf("%d\n",((n&0xAAAAAAAA)>>1) + (n&0x55555555) ); // prints 5
printf("%d\n",(n&0x55555555) + ((n&0xAAAAAAAA)>>1) ); // prints 5
return 0;
}
See http://ideone.com/d3mHT
Problem
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; } ``` http://ideone.com/B33YB