简体   繁体   中英

C++ Bit masking with AND operation within if statement

I have an integer input and I should check every bit, whether it's 0 or 1. I have a code example that should print "result is 0", but it printed "result is 1".

#include <iostream>

using namespace std;
int main() {
    int mask = 0x80;
    int input = 0x03;
    if ((mask && input) == 0) {
        cout << "result is 0" << endl; 
    } else {
        cout << "result is 1" << endl;
    }
}

if ((mask && input) == 0) . && is the logical AND operator. Because both mask and input is not equal to 0, it will return true . (true && true) is true , true == 0 is false . The condition is false , so everything in else get executed, hence the result.

You should change && to & (bitwise AND operator)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM