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

Masking bits with `&`

Masking bits with &

What you'll learn: How to use the bitwise AND operator to isolate or "filter" specific bits in a byte while ignoring the rest.

The Concept of Masking

In the physical world, a stencil is a piece of paper with holes cut into it. When you spray paint over the stencil, the paint only hits the surface where the holes are, leaving the rest untouched.

In C, the bitwise AND operator (&) acts exactly like that stencil. When you combine two numbers using &, the result will only have a 1 in positions where both numbers have a 1. If you want to check the status of one specific bit without looking at its neighbors, you use a "mask"—a number where only the bit you care about is set to 1.

How the & Logic Works

Imagine you have a byte representing a control panel with eight switches. You only care about the third switch from the right. To ignore everything else, you create a mask where only that third position is 1 (00000100).

When you apply mask & input:

  1. Any position in the mask that is 0 will force the result to be 0 (the "blocked" part of the stencil).
  2. Any position in the mask that is 1 will allow the original bit from the input to "show through."

Seeing it in Code

Here is how we isolate a single bit to check if it is "on" (1) or "off" (0).

#include <stdio.h>

int main() {
    // Binary: 00001101 (The number 13)
    unsigned char input = 13; 

    // We want to check the 3rd bit from the right (value 4)
    // Mask Binary: 00000100
    unsigned char mask = 4;

    // Apply the stencil
    unsigned char result = input & mask;

    if (result > 0) {
        printf("The bit is ON!\n");
    } else {
        printf("The bit is OFF!\n");
    }

    return 0;
}

In the example above, the & operation compares the input and mask bit-by-bit. Because the input has a 1 in the third position and the mask also has a 1 there, the result becomes 4 (00000100). If the input had a 0 there, the result would be 0. This allows us to "mask out" all the other data we don't need.

Key takeaway

Bitwise AND (&) acts as a stencil, allowing you to isolate specific bits by clearing all other positions to zero.