Reputation: 13
My question is simple: how do I perform a bitwise AND on an int
in C++?
#include <iostream>
int main() {
unsigned int foo = 3;
unsigned int bar = 6;
std::cout << foo & bar;
return 0;
}
Instead of outputting 2, it prints 3.
When I do any other bitwise operation, it also just prints the first variable.
How do I get it to do the operation?
Upvotes: 1
Views: 262
Reputation: 6086
You need to add parentheses around your foo & bar
because the &
operator has a lower precedence than the shift <<
operator.
std::cout << (foo & bar);
As a side note, I am surprised that the code compiles without the parentheses. Bonus: the doc for operator precedence rules on cppreference
Upvotes: 7