Simple boolean operators for bit flags

John picture John · Nov 16, 2010 · Viewed 16.4k times · Source

I am attempting to learn more about this to implement in my project.

I currently have got this basically:

unsigned char flags = 0; //8 bits

flags |= 0x2; //apply random flag

if(flags & 0x2) {
   printf("Opt 2 set");
}

Now I am wishing to do a little more complex things, what I am wanting to do is apply three flags like this:

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

And then remove flags 0x1 and 0x2 from it? I thought I could do something like this applying bitwise NOT (and bitwise AND to apply it):

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

Apparently they remain there or something either way when I check.

I also do not know how to check if they do NOT exist in the bit flags (so I cannot check if my previous code works), would it be something like this?

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

I can not find any resources from my recent searches that apply to this, I am willing to learn this to teach others, I am really interested. I apologize if this is confusing or simple.

Answer

cdhowie picture cdhowie · Nov 16, 2010

And the remove two from it? I thought I could do something like this:

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

to remove those two flags, but apparently they remain there or something either way.

That is the correct way to remove flags. If you printf("%d\n", flags) after that line, the output should be 4.

I also do not know how to check if they do NOT exist in the bit flag (so I cannot check if my previous code works), would it be something like this?

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

Nope:

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

EDIT:

To test for the presence of multiple flags:

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

To test for the absence of multiple flags, just compare to 0 as before:

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