按位运算比较结果错误

时间:2016-09-16 08:19:25

标签: c++ bit-manipulation bitwise-operators

我必须在这里做错事:我有这个枚举

enum OperetionFlags
{
        NONE = 0x01,
        TOUCHED = 0x02,
        MOVE_RIGHT = 0x04,
        MOVE_LEFT = 0x08,
        GAME_START = 0x10,
        GAME_END = 0x20
};

int curentState ;

没有我的程序启动,我设置:

main()
{
    curentState = 0 

    if (( curentState & GAME_START) == 0)
    {
        curentState |= GAME_START;
    }

    if ((curentState & MOVE_RIGHT) == 0)
    {
        curentState |= TOUCHED & MOVE_RIGHT;
    }

    if (curentState & GAME_START)
    {
        if (curentState & TOUCHED & MOVE_RIGHT) // HERE IS WHERE IT FAILED
        {

        }
    }

}

the curentState& TOUCHED& MOVE_RIGHT即使我设置了TOUCHED& MOVE_RIGHT位开启

2 个答案:

答案 0 :(得分:3)

使用按位运算,|类似于按位加法,&类似于按位乘法(如果有则丢弃进位)。
(很容易认为a & b是“a中的一位和b中的一位”,但它是“a和b中的一位”。)

让我们一起来:

curentState = 0 

    curentState is 00000000

if (( curentState & GAME_START) == 0)
{
    curentState |= GAME_START;
}

    curentState is now 00010000

if ((curentState & MOVE_RIGHT) == 0)
{
    curentState |= TOUCHED & MOVE_RIGHT;

        TOUCHED & MOVE_RIGHT is 00000000
        so curentState is still 00010000
}

if (curentState & GAME_START)
{
        curentState & TOUCHED is 00010000 & 00000010 = 00000000
        and 00000000 & MOVE_RIGHT is 00000000      

    if (curentState & TOUCHED & MOVE_RIGHT) // HERE IS WHERE IT FAILED
    {
    }
}

如果要设置这两个位,则需要使用|; TOUCHED | MOVE_RIGHT

如果你想测试这两个位,你需要非常详细:

(curentState & (TOUCHED | MOVE_RIGHT)) == (TOUCHED | MOVE_RIGHT)

或使用逻辑and

单独测试它们
(curentState & TOUCHED) && (curentState & MOVE_RIGHT)

答案 1 :(得分:0)

尝试

segmented