Simple boolean operators for bit flags
Asked Answered
K

2

9

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.

Kesha answered 16/11, 2010 at 6:16 Comment(0)
F
23

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");
Fortuna answered 16/11, 2010 at 6:19 Comment(4)
Sure, no problem. Bitwise operators are fun. :)Fortuna
Now how would I check if two flags were set without boolean and? like if(flags & (0x1 | 0x2)) but that appears to work even if I only set 0x1..Kesha
This has answered all my questions plus more, I am so glad for this. Thank you again. :)Kesha
No problem, that's what I'm here for. ;)Fortuna
V
11

I'm not sure why you think that clearing operation won't work.

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

is the correct way to do it. The operation to check if a bit isn't set is:

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

The one you have:

if (flags & ~0x2) ...

will be true if any other bit is set, which is probably why you thing the clearing operation isn't working. The problem lies not with the clearing but with the checking.

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

if ((flags & (0x2|0x1)) == 0x2|0x1) ...
Valdes answered 16/11, 2010 at 6:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.