How to Set Multiple Bits at Once in Embedded C
In embedded C, you can set multiple bits at once by using the bitwise OR operator
| with a mask that has 1s in the bit positions you want to set. For example, PORT |= (1 << 2) | (1 << 4); sets bits 2 and 4 simultaneously.Syntax
To set multiple bits at once, use the bitwise OR operator |= with a mask combining all bits you want to set. Each bit is represented by 1 << n, where n is the bit position (starting from 0).
PORT: The register or variable where bits are set.|=: Bitwise OR assignment operator.(1 << n): Creates a mask with bitnset to 1.|: Combines multiple bit masks.
c
PORT |= (1 << bit1) | (1 << bit2) | (1 << bit3);
Example
This example shows how to set bits 1, 3, and 5 of a byte variable PORT. It prints the value before and after setting the bits.
c
#include <stdio.h> int main() { unsigned char PORT = 0x00; // All bits cleared printf("Before setting bits: 0x%02X\n", PORT); // Set bits 1, 3, and 5 PORT |= (1 << 1) | (1 << 3) | (1 << 5); printf("After setting bits: 0x%02X\n", PORT); return 0; }
Output
Before setting bits: 0x00
After setting bits: 0x2A
Common Pitfalls
Common mistakes when setting multiple bits include:
- Using
=instead of|=, which overwrites all bits instead of setting specific ones. - Not using parentheses around bit masks, causing operator precedence errors.
- Shifting by a bit position outside the variable size (e.g., shifting by 8 in an 8-bit variable).
c
// Wrong: overwrites all bits PORT = (1 << 1) | (1 << 3); // This clears other bits unintentionally // Right: sets bits without clearing others PORT |= (1 << 1) | (1 << 3);
Quick Reference
| Operation | Description | Example |
|---|---|---|
| Set bits | Set specific bits to 1 without changing others | PORT |= (1 << 2) | (1 << 4); |
| Clear bits | Clear specific bits to 0 | PORT &= ~((1 << 2) | (1 << 4)); |
| Toggle bits | Flip specific bits | PORT ^= (1 << 2) | (1 << 4); |
| Check bit | Check if a bit is set | (PORT & (1 << 2)) != 0 |
Key Takeaways
Use bitwise OR (|=) with a combined mask to set multiple bits at once.
Create masks with (1 << bit_position) for each bit you want to set.
Always use parentheses to group bit masks correctly.
Avoid using = which overwrites all bits instead of setting specific ones.
Check bit positions to avoid shifting outside variable size.