按位运算比较结果错误
Bitwise operation compare result is wrong
我一定是哪里做错了:我有这个枚举
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
{
}
}
}
curentState & TOUCHED & MOVE_RIGHT 即使我将 TOUCHED & MOVE_RIGHT 位设置为 on
也是错误的
尝试
curentState |= TOUCHED | MOVE_RIGHT;
对于按位运算,|
类似于按位加法,&
类似于按位乘法(如果有进位则丢弃进位)。
(很容易认为a & b
是"the one bits from a and the one bits from b",其实是"the bits that are one in both a and 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)
我一定是哪里做错了:我有这个枚举
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
{
}
}
}
curentState & TOUCHED & MOVE_RIGHT 即使我将 TOUCHED & MOVE_RIGHT 位设置为 on
也是错误的尝试
curentState |= TOUCHED | MOVE_RIGHT;
对于按位运算,|
类似于按位加法,&
类似于按位乘法(如果有进位则丢弃进位)。
(很容易认为a & b
是"the one bits from a and the one bits from b",其实是"the bits that are one in both a and 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)