c++ - Simple boolean operators for bit flags -


i attempting learn more implement in project.

i have got basically:

unsigned char flags = 0; //8 bits  flags |= 0x2; //apply random flag  if(flags & 0x2) {    printf("opt 2 set"); } 

now wishing little more complex things, wanting apply 3 flags this:

flags = (0x1 | 0x2 | 0x4); 

and remove flags 0x1 , 0x2 it? thought applying bitwise not (and bitwise , apply it):

flags &= ~(0x1 | 0x2); 

apparently remain there or either way when check.

i not know how check if not exist in bit flags (so cannot check if previous code works), this?

if(flags & ~0x2)      printf("flag 2 not set"); 

i can not find resources recent searches apply this, willing learn teach others, interested. apologize if confusing or simple.

and remove 2 it? thought this:

flags &= ~(0x1 | 0x2); 

to remove 2 flags, apparently remain there or either way.

that correct way remove flags. if printf("%d\n", flags) after line, output should 4.

i not know how check if not exist in bit flag (so cannot check if previous code works), this?

if(flags & ~0x2)      printf("flag 2 not set"); 

nope:

if ((flags & 0x2) == 0)     printf("flag 2 not set"); 

edit:

to test presence of multiple flags:

if ((flags & (0x1 | 0x2)) == (0x1 | 0x2))     printf("flags 1 , 2 set\n"); 

to test absence of multiple flags, compare 0 before:

if ((flags & (0x1 | 0x2)) == 0)     printf("flags 1 , 2 not set (but maybe 1 of them is!)\n"); 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

aspxgridview - Devexpress grid - header filter does not work if column is initially hidden -

c# - How to execute a particular part of code asynchronously in a class -