按位AND的好奇行为

时间:2013-10-28 09:32:38

标签: c++ bit-manipulation bits

我正在编码,以下代码未提供所需的输出。当pos除以2时,pos& 1应该返回余数。当我用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<<"blue\n";
    }
    else
    cout<<"red\n";
    return 0;
}

1 个答案:

答案 0 :(得分:11)

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