按位操作比较结果错误
Bitwise operation compare result is wrong
我这里一定做错了什么:我有这个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;
相关文章:
- 如何修复循环中的错误产生的错误结果?
- 添加可变参数函数的错误结果
- 使用特征 3 线性系统求解器的错误结果
- 按位包含 OR 的错误结果
- 如果我将索引变量更改为零,并且合并函数中的k = 0,则获得合并排序的错误结果
- STD :: FPCLASSIFY的错误结果使用Valgrind进行长时间的双重双重结果
- 视觉工作室的错误结果
- 将C#struct传递给C 不受管理的DLL返回错误结果
- 最长的常见子字错误结果
- 华氏度到摄氏度的错误结果
- UE4中简单坐标变换的错误结果
- 记忆错误结果的说明[编译器行为]
- 如何解决错误PRJ0002:错误结果 -1073741515从"cl.exe"返回?
- 错误 PRJ0002:错误结果 -1073741515 从"C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\cl.
- glGetUniformLocation OpenGL ES 2.0(在ipad 3 iOS 7.0.3上返回错误结果)
- 在模板函数中调用std::for_each时出现错误结果
- 使用copy和back_inserter将矢量附加到其自身时出现错误结果
- CUDA 线程在全局内存中的私有位置写入时出现错误结果
- 来自 c++ 代码的错误结果
- 使用浮点值和铸造的算术运算的错误结果 - 差异很大,我想这不是准确值的情况(429497)?