Useful Bitwise tips

When it comes to maintaining state of an entity, bitwise operator plays an important role.Consider that you are developing a game and your character can have jump, walk, fire and run states. The characters can be in more than 2 states at any point of time.You can store this information easily using bitwise operators.

Define states of the player.

typedef enum {
eNone = 0, (0000 0000)
eRunning =1, (0000 0001)
eJumping =2, (0000 0010)
eWalking =4, (0000 0100)
eShooting =8 (0000 1000)
}EPlayerState;

Consider you want to set the player state to Running, you can do this by ORing.

0000 0000
0000 0001     (eRunning)
------------  (Bitwise OR)
0000 0001
------------

You can set another state like Shooting.

0000 0001     (Current state)
0000 1000     (eShooting)
------------  (Bitwise OR)
0000 1001
------------

We have captured both the states of the player.
To query the state ‘x’ of the player, you simply need to AND it.
To check if the player is Running or not,

0000 1001     (Current State)
0000 0001     (eRunning)
-----------   (Bitwise AND)
0000 0001
-----------

To reset any state, you need complement the state and then AND it.
To reset ‘Shooting’ state,

Complement the Shooting state.

0000 1000 -> 1111 0111 (complement)

Now AND it. This will reset only the ‘Shooting’ state and retain all the other states of the player.

0000 1001     (Current State)
1111 0111
-----------   (Bitwise AND)
0000 0001
-----------

These are the convenient methods.

-(void)setState:(EPlayerState)state
{
_playerSate = _playerSate|state;
}

-(void)resetState:(EPlayerState)state
{
_playerSate = _playerSate & (~state);
}

-(BOOL)isStateSet:(EPlayerState)state
{
BOOL isSet = _playerSate & state;
return isSet;
}

Advertisements