Course contentsShow
← C
Lesson 188 of 1,2193. Operators and ExpressionsFree lesson

Common bitwise idioms

Common bitwise idioms

What you'll learn: How to use bitwise operators as clever "shortcuts" for checking and modifying specific bits within an integer.

In C programming, we often treat an integer not as a single number, but as a collection of individual switches (bits). To control these switches efficiently, programmers use "idioms"—standard patterns that perform specific tasks like checking if a setting is turned on or forcing a specific bit to turn off.

The "Mask" Analogy

Think of a mask as a piece of paper with a single hole punched in it. If you lay it over a row of light switches, you can only see the switch behind the hole. In C, we create a mask by shifting the number 1 to a specific position. For example, (1 << 3) creates a binary mask where only the third bit is active (00001000).

Checking a bit (The AND idiom)

To see if a specific bit is "1," we use the Bitwise AND (&). Because & only results in a 1 if both sides are 1, using our mask will zero out everything except the bit we care about. If the result is non-zero, the bit was on.

Toggling and clearing bits

We use Bitwise OR (|) to force a bit to 1 without changing any other bits. Conversely, to force a bit to 0, we combine the Bitwise AND with the NOT (~) operator. This "flips" the mask, creating a row of 1s with a single 0 at our target position.

#include <stdio.h>

int main() {
    unsigned char settings = 0b00000100; // Third bit is currently ON
    int mask = (1 << 3);                 // Target the 4th bit (index 3)

    // IDIOM 1: Set a bit (Force it to be 1)
    settings |= mask; 
    
    // IDIOM 2: Check a bit
    if (settings & mask) {
        printf("The 4th bit is active!\n");
    }

    // IDIOM 3: Clear a bit (Force it to be 0)
    settings &= ~mask;

    return 0;
}

Why use idioms?

These patterns are the bread and butter of low-level programming. Whether you are controlling hardware pins or saving memory by packing multiple "Yes/No" options into a single variable, these idioms allow you to perform surgical strikes on your data without disturbing the surrounding bits.

Key takeaway

Bitwise idioms use masks and logical operators to check, set, or clear specific bits within a variable without affecting the rest of the data.