Remove bits from number

boolean-logic, math

Solution

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;

Problem

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?

Original source