Setting, Clearing, and Toggling Bits in C
Bit manipulation is a fundamental technique in the C programming
language that allows developers to modify individual bits—commonly
called flags—within an integer variable. By combining bitwise operators
such as AND (&), OR (|), XOR
(^), and NOT (~) with shift operators
(<<), you can alter a specific bit's state without
affecting neighboring bits. This article explains the underlying
algorithmic mechanics for setting, clearing, and toggling an arbitrary
bit n (where n is a zero-indexed
position).
The Bitmask
Every single-bit operation relies on creating a mask that targets
position n. In C, this mask is constructed using the
bitwise left-shift operator:
(1U << n)This shifts an unsigned binary 1 leftward by
n positions, creating a binary number containing a single
1 at position n and 0s everywhere
else. Using 1U ensures unsigned arithmetic to avoid
undefined behavior associated with signed integer overflow.
1. Setting a Bit (Changing to 1)
To set a bit to 1 regardless of its current state, use
the bitwise OR operator (|).
Algorithm:
flags = flags | (1U << n);
// Or using compound assignment:
flags |= (1U << n);How it works:
- The truth table for OR dictates that
X | 1 = 1andX | 0 = X. - When the target bit is compared with the mask's
1, it is guaranteed to become1. - All other bits are compared with
0, leaving their original values unchanged.
2. Clearing a Bit (Changing to 0)
To reset a bit to 0 regardless of its current state, use
the bitwise AND operator (&) with the
bitwise NOT (complement) operator (~).
Algorithm:
flags = flags & ~(1U << n);
// Or using compound assignment:
flags &= ~(1U << n);How it works:
- The mask
(1U << n)has a1at indexnand0elsewhere. - The complement
~(1U << n)inverts this mask, producing a0at indexnand1s at all other positions. - The truth table for AND dictates that
X & 0 = 0andX & 1 = X. - Applying
&forces indexnto0while preserving every other bit.
3. Toggling a Bit (Inverting the State)
To flip a bit from 0 to 1 or from
1 to 0, use the bitwise XOR
(exclusive OR) operator (^).
Algorithm:
flags = flags ^ (1U << n);
// Or using compound assignment:
flags ^= (1U << n);How it works:
- The truth table for XOR dictates that
X ^ 1 = ~XandX ^ 0 = X. - Evaluating index
nagainst1flips its value (0 ^ 1 = 1, and1 ^ 1 = 0). - All other bits are compared against
0, retaining their original values.
4. Checking a Bit's State
To evaluate whether bit n is set (1) or
cleared (0), extract it using the bitwise AND operator:
int is_set = (flags & (1U << n)) != 0;If the bit at index n is 1, the expression
yields a non-zero value; if it is 0, the result is
0.