Skip to main content
GameDev.net gamedev.net
🔒 Locked

C++ flags and the bitwise OR operator

Started by retroworld Jul 4, 2010 at 3:52 AM 3 replies 2.2k views
Original Post
retroworld
retroworld
hello. I am a C++ programmer and I have knowlage on how the bitwise operator works but in some functions such as in SDL the Initialising function:
SDL_INIT(SDL_INIT_VIDEO | SDL_INIT_JOYSTICK)


how does tht actually work because SDL_INIT only takes in one arguement?
Brother Bob
Brother Bob
The result of the bitwise OR is a single value. Other than what the actual result is, it's no different from
SDL_INIT(SDL_INIT_VIDEO + SDL_INIT_JOYSTICK)

Addition adds two values and returns the result, which is passed to the function. Bitwise OR also takes two operands and returns the result.
retroworld
retroworld
so lets say
 SDL_INIT_VIDEO 
is equal to 1 and
 SDL_INIT_JOYSTICK 
is equal to 4. so that means 1 | 4. so in binary is it going to be

00000001
00000100
-----------
00000101

which means 5.

and how does the function work with that?
KulSeran
KulSeran
To expand on that... some common operations using flags.

1) You have to assume that each "flag" is a unique bit pattern, so that no two flags share bits unless they mean the same thing.
2) You can combine any flags with |
flagC = (flagA | flagB)

yields some integer that contains the information of both flags.

3) You can test for a flag with &
(flagC & flagA) => flagA

any non-zero result from the flag test means that the flag was there.

You can combine your flags in a test as well
(flagC & (flagA | flagB) ) => flagA | flagB


4) You can remove a flag with 'not' and 'and'
flagC & ~flagA => flagB



For something like collision, you could do tests like:
if( objectFlags & (ENEMY | ZOMBIE) == (ENEMY | 0) ){// do effect that hurts any enemy that is not a zombie...}if( objectFlags & (ENEMY) ){// do effects that hurt all enemies...}if( objectFlags & (ZOMBIE) ){// do effects that only hurt zombies...}

whre objectFlags is a single number generated from ORing together flags like
ENEMY = 1<<0ZOMBIE = 1<<1PLAYER = 1<<2ENVIRONMENT = 1<<3


note: 1<1<<0 = 0001
1<<1 = 0010
1<<2 = 0100
...etc
the >> operator does the oposite, but has some special considerations on signed numbers.
For unsigned numbers, it yields
0100 >> 2 = 0001

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.