# Options joined with |

• 04-16-2003
roktsyntst
Options joined with |
I'm writing a class that I want to be able to accept several options with one parameter, similar to the way you can specify setiosflags( ios::fixed | ios::showpoint )

I tried to check the type of some of these ios flags, but they are enum's, which doesn't help me very much. I understand that for int's, the | operator effectively adds them ( 5 | 2 = 7, for example ), and that by using ints with values that are powers of 2, one can figure out which combination of objects was passed by looking at the sum. Is that usually how it's done (using int's)? If so, is there an easy way to break the sum down into the individual combinations? The only way I can think of immediately is to divide by the highest power of 2 that leaves a power of 2 as a remainder, but it seems like it could be easier...TIA for any help.
• 04-16-2003
MrWizard
The bitwise OR operator does not necessarily add the two numbers. It may work for 5 and 2 but try 3 and 1. You will still get 3. It just OR's the bits of the 2 numbers. You can look up the truth tables online somewhere.

Try using each power of 2 as a flag. Like.

Code:

```#define EFFECT_1  0x000F #define EFFECT_2  0x00F0 #define EFFECT_3  0x0F00 #define EFFECT_4  0xF000```
That way if you have an int or something full of effects, which you SET by
Code:

`int effect |= EFFECT_1;`

To CHECK an effect do this.
Code:

```if( effect & EFFECT_4 ) {   // Effect 4 is on }```
Hope this helps a little.
• 04-16-2003
Magos
Quote:

I understand that for int's, the | operator effectively adds them ( 5 | 2 = 7, for example )
Not really. That only applies if both numbers have no set bits in common:

5 | 2 = 101 | 010 = 111 = 7
5 | 4 = 101 | 100 = 101 = 5

Anyway, back to your question... which I didn't really get :rolleyes:. It is true that flags are numbers written on the form 2^n (0 <= n <= MAXBITS), and that you can store several flags in one variable.

To set one flag, use:
FlagStorage |= Flag;

To clear one flag, use:
(MAXVALUE is the greatest value for the datatype of FlagStorage, ie 255 for a char)
FlagStorage &= (MAXVALUE - Flag);

To toggle one flag, use:
FlagStorage ^= Flag;

To retrieve one flag, use:
bool IsItSet = (FlagStorage & Flag);

EDIT:
Damn, not just beaten once but beaten twice... :( ... :D
• 04-16-2003
Stoned_Coder
Quote:

FlagStorage &= (MAXVALUE - Flag);
cmon magos you can do better than that....

dont forget there is a ~ operator.

FlagStorage &= ~Flag
• 04-16-2003
Magos
Quote:

Originally posted by Stoned_Coder
cmon magos you can do better than that....

dont forget there is a ~ operator.

FlagStorage &= ~Flag

Bah, ok then...
You win this one :D
• 04-16-2003
roktsyntst
Thanks, all, especially Salem and Wizard. That's exactly what I needed to know, and thanks for clearing up the bit about | and adding.