Simple logical operators for bit flags

I am trying to learn more about this for implementation in my project.

Currently, I got this mostly:

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

Now I want to do a few more complicated things, what I want to do is apply three type flags:

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

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

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

Apparently they stay there or something anyway when I check.

I also don’t know how to check if they exist in the bit flags (so I can’t check if my previous code is working), would there be something like this?

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

I can’t find any resources from my recent searches that apply to this, I’m ready to learn how to teach others, I’m really interested. I apologize if this is confusing or simple.

+7
c ++ c boolean-operations bitflags
source share
2 answers

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

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

to remove these two flags, but apparently they stay there or something anyway.

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

I also don’t know how to check if they DO NOT exist in the bit flag (so I can’t check if my previous code worked), would there be something like this?

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

Nope

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

EDIT:

Check for multiple flags:

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

To check for the absence of multiple flags, compare only with 0:

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

I'm not sure why you think the cleanup operation will not work.

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

is the right way to do this. Operation to check if a bit is set:

 if (!(flags & 0x2)) ... 

The one you have:

 if (flags & ~0x2) ... 

will be true if any other bit is set, which is probably the reason that the cleanup operation does not work. The problem is not cleaning, but checking.

If you want to check that all bits in a group are set:

 if ((flags & (0x2|0x1)) == 0x2|0x1) ... 
+11
source share

All Articles