按位 AND 的奇怪行为

Curious behaviour of bitwise AND

本文关键字:AND 按位      更新时间:2023-10-16

我正在编码,以下代码没有给出所需的输出。 pos&1 应该在 POS 除以 2 时返回余数。当我用pos%2替换pos&1时,一切正常。可能是什么问题?

#include <iostream>
using namespace std;
int main(){
    int y;
    unsigned long long int pos;
    cin>>y;
    cin>>pos;
    int f=0;
    while(y>0){
        y--;
        if(pos&1==0){
            f=1-f;
        }
        pos=pos/2;
    }
    if(f==1){
        cout<<"bluen";
    }
    else
    cout<<"redn";
    return 0;
}
1==0

pos&1更优先。试试if((pos&1)==0){