0
0
Power-electronicsHow-ToBeginner · 3 min read

How to Check if a Bit is Set in Embedded C: Simple Guide

In embedded C, you check if a bit is set by using the bitwise AND operator & with a mask that has a 1 in the bit position you want to check. If the result is not zero, the bit is set. For example, if (value & (1 << bit_position)) checks if the bit at bit_position is set in value.
📐

Syntax

To check if a bit is set, use the bitwise AND operator & with a mask created by shifting 1 to the bit position you want to check.

  • value: The variable holding the bits.
  • bit_position: The zero-based position of the bit to check (0 is the least significant bit).
  • 1 << bit_position: Creates a mask with only the target bit set.
  • value & (1 << bit_position): Checks if that bit is set.
c
if (value & (1 << bit_position)) {
    // bit is set
} else {
    // bit is not set
}
💻

Example

This example shows how to check if the 3rd bit (bit position 2) is set in a byte variable.

c
#include <stdio.h>

int main() {
    unsigned char value = 0b00001100; // binary: bits 2 and 3 are set
    int bit_position = 2;

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

    return 0;
}
Output
Bit 2 is set.
⚠️

Common Pitfalls

Common mistakes when checking bits include:

  • Using = instead of & which assigns instead of checks.
  • Not using parentheses around the shift operation, causing wrong precedence.
  • Checking the wrong bit position (remember bit positions start at 0).
  • Forgetting that the result of & is zero or non-zero, so always compare to zero or use it directly in conditions.
c
/* Wrong way: assignment instead of bitwise AND */
if (value = (1 << bit_position)) {
    // This sets value, does not check bit
}

/* Correct way: use bitwise AND with parentheses */
if (value & (1 << bit_position)) {
    // Bit is set
}
📊

Quick Reference

OperationDescriptionExample
Check bit setUse bitwise AND with maskif (value & (1 << bit_position))
Create maskShift 1 left by bit position1 << bit_position
Bit positionsStart at 0 for least significant bitbit 0 is rightmost bit
ResultNon-zero means bit is setif (result != 0) or if (result)

Key Takeaways

Use bitwise AND with a shifted 1 to check if a bit is set.
Remember bit positions start at 0 from the right (least significant bit).
Always use parentheses around the shift operation for correct precedence.
Check if the result is non-zero to confirm the bit is set.
Avoid using assignment (=) instead of bitwise AND (&) when checking bits.