Reputation: 7214
I have some bit flag, where:
A = 1 (0001)
B = 2 (0010)
C = 4 (0100)
D = 8 (1000)
I would like to set bit A and C in my flag: flag = A | C
Now my flag is 5 (0101).
I need to delete bit C from flag. How can I do this?
Upvotes: 3
Views: 2590
Reputation: 213120
To clear a flag you typically AND
with its complement, e.g. in C and related languages:
x = 5; // x = 0101
x = x & ~C; // x = x & 1011 = 0101 & 1011 = 0001
Note: this can be expressed slightly more succinctly as:
x &= ~C;
Alternatively if you already know that a particular bit is 1 and you want to set it to 0 then you can just toggle (invert) it using XOR:
x = x ^ C; // x = x ^ 0100 = 0101 ^ 0100 = 0001
or:
x ^= C;
Upvotes: 5
Reputation: 7214
My solution is:
1) Check, is bit set
flag & C == C
2) If bit set apply XOR operation:
flag ^ C
Now my flag is 5 (0001).
May be there are more simple solutions?
Upvotes: 0