Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggling enum values as bit flags

I have a certain set of available enumed options

typdef enum { 
option1 = 1 << 0,
option2 = 1 << 1,
option3 = 1 << 2,
} availableOptions;

I want to toggle them off and on according to an input from the user before executing them.

For instance:

// iniatially set to all options
myOption = option1 | option2 | option3;

// after some input from the user

void toggleOption1()
{
  // how can I toggle an option that was already set without impacting the other options
}
like image 486
Avner Barr Avatar asked Nov 17 '13 14:11

Avner Barr


1 Answers

Use bit-wise XOR:

void toggleOption1()
{
    myOption ^= option1;
}

The caret symbol ^ is the bit-wise XOR operator. The statement:

a ^= b;

flips only the bits in a where the corresponding bit in b is set. All other bits are left alone.

like image 163
godel9 Avatar answered Oct 21 '22 21:10

godel9