0
0
Embedded Cprogramming~5 mins

Checking if a bit is set in Embedded C

Choose your learning style9 modes available
Introduction
Sometimes you need to know if a specific switch or flag is turned on inside a number. Checking if a bit is set helps you find that out easily.
When you want to see if a particular feature or option is active in a device.
When reading sensor status flags stored as bits in a number.
When controlling hardware pins and you need to check if a pin is high or low.
When debugging or monitoring specific bits in a control register.
Syntax
Embedded C
if (number & (1 << bit_position)) {
    // bit is set
} else {
    // bit is not set
}
The bit_position starts from 0 for the least significant bit (rightmost bit).
The expression (1 << bit_position) creates a mask with only that bit set.
Examples
Check if the rightmost bit (bit 0) is set in number 5 (0101). It is set because bit 0 is 1.
Embedded C
int number = 5; // binary 0101
int bit_position = 0;
if (number & (1 << bit_position)) {
    // bit 0 is set
}
Check if bit 3 is set in number 8 (1000). It is set because bit 3 is 1.
Embedded C
int number = 8; // binary 1000
int bit_position = 3;
if (number & (1 << bit_position)) {
    // bit 3 is set
}
Check if bit 1 is set in number 2 (0010). It is set because bit 1 is 1.
Embedded C
int number = 2; // binary 0010
int bit_position = 1;
if (number & (1 << bit_position)) {
    // bit 1 is set
}
Sample Program
This program checks if bit 2 is set in the number 13 (binary 1101). Bit 2 is the third bit from the right, which is 1 here, so it prints that the bit is set.
Embedded C
#include <stdio.h>

int main() {
    unsigned int number = 13; // binary 1101
    int bit_position = 2;

    if (number & (1 << bit_position)) {
        printf("Bit %d is set in number %u.\n", bit_position, number);
    } else {
        printf("Bit %d is not set in number %u.\n", bit_position, number);
    }

    return 0;
}
OutputSuccess
Important Notes
Remember bits are counted from 0 starting at the rightmost bit.
Using bitwise AND (&) with a mask isolates the bit you want to check.
If the result is not zero, the bit is set; otherwise, it is not.
Summary
Use (1 << bit_position) to create a mask for the bit you want to check.
Use bitwise AND (&) between the number and the mask to test the bit.
If the result is non-zero, the bit is set; if zero, it is not.