Home

Checking Bits in C: The Logic of the Mask

Checking Bits in C: The Logic of the “Mask”

To understand which bit we are targeting, we have to look at how they are labeled. In binary, we always count from right to left, and in programming, we start counting at 0. For example, in a number like 0b1011, the bit on the far right is “Bit 0,” and the next one over is “Bit 1.”

Here is a simple C program to illustrate that point:

#include <stdio.h>

int main(void)
{
    int mask = 0b0010;  // Our "filter" for the 2nd bit (Index 1)
    int num = 0b1011;   // The number we want to check (Decimal 11)

    int result = mask & num;

    // %04b tells C: "Print in binary, at least 4 digits wide, padding with 0s"
    printf("Bitwise AND operation result: %04b\n", result);
    printf("Bitwise AND operation result (decimal): %d\n", result);

    return 0;
}

Understanding the Output

When you run this code, the output is: Bitwise AND operation result: 0010 Bitwise AND operation result (decimal): 2

Why 2? In C, the result of a bitwise operation is still a number. Because the mask “filtered” everything out except for the 2nd bit, the final binary result was 0b0010. In our standard decimal system, 0b0010 equals 2.

How the AND (&) Operation Works

The & operator compares each column of bits. It only returns a 1 if both the number and the mask have a 1 in that position. We are checking the 2nd bit (which is Index 1).

The Visual Calculation:

1 0 1 1 (num) & 0 0 1 0 (mask) -—— 0 0 1 0 (result)

Because the mask only has a 1 in the second position, it forces all other bits in the result to become 0.

Introduction to the Binary System

The 0b prefix tells the computer: “Read the following digits as bits (Base-2), not as tens or hundreds (Base-10).”

To make it absolutely clear what position relates to what bit in our example:

Why go from right to left?

This is the same way we handle decimal numbers. In the number 125, the 5 is the smallest value (the “ones”) and the 1 is the largest (the “hundreds”).

In binary, the far right is the Least Significant Bit. By keeping the smallest value on the right, the math stays consistent and the bit index matches the exponent (e.g., Bit 3 is always calculated as 2^3).

Tags: LearningCProgramming