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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With