Bit Masks in C: Using AND, OR, and XOR

A bit mask is a predefined sequence of bits used to selectively view, modify, or toggle specific bits within a larger byte or integer. In C programming, bit masks are essential for low-level systems programming, embedded devices, and performance-critical applications where packing multiple boolean states or flags into a single integer saves memory and processing cycles. This guide explains the core concepts of bit masks and demonstrates how to manipulate them efficiently using C's bitwise AND (&), OR (|), and XOR (^) operators.

What is a Bit Mask?

A bit mask acts as a filter over binary data. By setting specific bits to 1 or 0 in the mask, you define which bits of a target variable you want to target. In C, masks are typically constructed using unsigned integers and the bitwise left-shift operator (<<).

For example, to target the third bit (index 2) of a byte:

#define FLAG_A (1 << 0) // 00000001
#define FLAG_B (1 << 1) // 00000010
#define FLAG_C (1 << 2) // 00000100

Setting Bits with Bitwise OR (|)

The bitwise OR operator compares corresponding bits of two operands. If either bit is 1, the resulting bit is 1; it is 0 only if both bits are 0.

Because x | 1 = 1 and x | 0 = x, the OR operator is used to turn on (set to 1) specific bits in a variable without altering the remaining bits.

unsigned char status = 0; // 00000000

// Turn on FLAG_A and FLAG_C
status |= FLAG_A;         // 00000001
status |= FLAG_C;         // 00000101

Checking and Clearing Bits with Bitwise AND (&)

The bitwise AND operator evaluates to 1 only if both corresponding bits are 1. If either bit is 0, the result is 0.

Checking a Bit

To test whether a specific bit is set, apply the bit mask with &. If the bit is set, the expression evaluates to a non-zero value.

if (status & FLAG_A) {
    // Executes if FLAG_A is set
}

Clearing a Bit

Because x & 0 = 0 and x & 1 = x, clearing (turning off) a bit requires combining the bitwise AND operator with the bitwise NOT operator (~). Inverting the mask creates a pattern where the target bit is 0 and all other bits are 1.

// Turn off FLAG_A
status &= ~FLAG_A; // status & 11111110

Toggling Bits with Bitwise XOR (^)

The bitwise XOR (exclusive OR) operator returns 1 if the corresponding bits are different, and 0 if they are identical.

Because x ^ 1 = ~x (flipping the bit) and x ^ 0 = x (leaving the bit unchanged), XOR is used to toggle a bit between 0 and 1.

// Toggle FLAG_C (if it is 1, it becomes 0; if it is 0, it becomes 1)
status ^= FLAG_C;

Summary of Operations

Operation Operator Expression Description
Set bit variable |= MASK; Turns the targeted bit(s) to 1.
Clear bit variable &= ~MASK; Turns the targeted bit(s) to 0.
Toggle bit variable ^= MASK; Inverts the targeted bit(s).
Check bit (variable & MASK) != 0 Evaluates to true if the bit is 1.