0
0
Power-electronicsHow-ToBeginner · 3 min read

How to Set a Bit in Embedded C: Simple Syntax and Example

To set a bit in embedded C, use the bitwise OR operator | with a mask that has the target bit set to 1. For example, variable |= (1 << bit_position); sets the bit at bit_position to 1 without changing other bits.
📐

Syntax

The syntax to set a bit in embedded C is:

variable |= (1 << bit_position);
  • variable: The integer variable whose bit you want to set.
  • 1 << bit_position: Creates a mask with only the bit at bit_position set to 1.
  • |=: Bitwise OR assignment operator that sets the specified bit without changing others.
c
variable |= (1 << bit_position);
💻

Example

This example shows how to set the 3rd bit (bit position 2, counting from 0) of an 8-bit variable.

c
#include <stdio.h>

int main() {
    unsigned char value = 0b00001000; // initial value with 4th bit set
    int bit_position = 2; // we want to set the 3rd bit (bit 2)

    printf("Before setting bit: 0x%02X\n", value);

    value |= (1 << bit_position); // set bit 2

    printf("After setting bit:  0x%02X\n", value);
    return 0;
}
Output
Before setting bit: 0x08 After setting bit: 0x0C
⚠️

Common Pitfalls

Common mistakes when setting bits include:

  • Using = instead of |=, which overwrites the entire variable instead of setting one bit.
  • Using the wrong bit position (remember bit positions start at 0).
  • Not using parentheses around 1 << bit_position, which can cause unexpected results due to operator precedence.
c
// Wrong way (overwrites all bits):
// variable = 1 << bit_position;

// Right way (sets only the target bit):
// variable |= (1 << bit_position);
📊

Quick Reference

OperationSyntaxDescription
Set bitvariable |= (1 << bit_position);Sets the bit at bit_position to 1
Clear bitvariable &= ~(1 << bit_position);Clears the bit at bit_position to 0
Toggle bitvariable ^= (1 << bit_position);Flips the bit at bit_position
Check bit(variable & (1 << bit_position)) != 0Checks if bit at bit_position is set

Key Takeaways

Use bitwise OR with a shifted 1 to set a specific bit without affecting others.
Always use parentheses around the shift operation to ensure correct precedence.
Bit positions start at 0 from the least significant bit (rightmost).
Avoid using = instead of |= to prevent overwriting the entire variable.
Use a mask like (1 << bit_position) to target the exact bit you want to set.