Search code examples
c++bit-manipulationbitwise-operators

Bitwise AND: why do I get this behaviour?


I have this simple program here:

#include <iostream>
#include <bitset>

using namespace std;

int main() {

unsigned char a = 0b11100111; 
if((a & (1<<2)) == true) // THIS IS THE LINE
    cout << "Entering if block!" << endl;
else
    cout << "Too bad, maybe next time.." << endl;
bitset<8> x(a & (1<<2));
cout << x << '\n';
}

Can you tell me why this if((a & (1<<2)) == true) outputs: Too bad, maybe next time.. 00000100

While this if((a & (1<<2)) outputs: Entering if block! 00000100

I'm compiling with g++ -std=c++14.


Solution

  • 0b100 is a number and shouldn't be compared against true.

    Try changing your if statement to:

    if (a & (1<<2))
    

    or equivalently

    if((a & (1<<2)) != 0)
    

    since in an if statement, anything not zero is considered true.