user63898 - 1 year ago 47

C++ Question

I must be doing something wrong here : I have this enum

`enum OperetionFlags`

{

NONE = 0x01,

TOUCHED = 0x02,

MOVE_RIGHT = 0x04,

MOVE_LEFT = 0x08,

GAME_START = 0x10,

GAME_END = 0x20

};

int curentState ;

no my program starts and i set :

`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 is false even that I set the TOUCHED & MOVE_RIGHT bits to on

Answer Source

With bitwise operations, `|`

is like bitwise addition and `&`

is like bitwise multiplication (dropping carry bits if there are any).

(It's very easy to think that `a & b`

is "the one bits from a and the one bits from b", but it's "the bits that are one in both a and b".)

Let's follow along:

```
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
{
}
}
```

If you want to set both bits, you need to use `|`

; `TOUCHED | MOVE_RIGHT`

.

If you want to test for both bits, you need to be very verbose:

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

or test them separately with the logical `and`

```
(curentState & TOUCHED) && (curentState & MOVE_RIGHT)
```