按位操作比较结果错误

Bitwise operation compare result is wrong

本文关键字:错误 结果 比较 位操作      更新时间:2023-10-16

我这里一定做错了什么:我有这个enum

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 currentstate &感动,MOVE_RIGHT是false,即使我设置了touch &

对于位运算,|类似于位加法,&类似于位乘法(如果有进位,则去掉)。
(很容易认为a & b是"来自a的1位和来自b的1位",但它是"在a和b中都是1的位"。)

让我们继续:

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)

try

 curentState |= TOUCHED | MOVE_RIGHT;