Home / Learn Embedded C / Setting a Bit
Setting a Bit
Turning on exactly one bit without disturbing any of the others.
The idea, explained simply
Definition
Setting bit N to 1 (without changing any other bit) is done with register |= (1 << N) — OR-ing in a mask that has only that one bit set.
Why you need this
Turning on one GPIO pin, or one feature flag in a control register, must never disturb the other 7, 15 or 31 bits sharing that same register — this is the single most common register operation in embedded C.
How it works
OR with a 1 in a position always forces that position to 1, while OR-ing with a 0 anywhere else leaves those positions completely unchanged — exactly the "touch only this one bit" behavior needed.
Where you'll see this
- GPIO pin control
- Enabling a feature flag
- Register configuration
Try it
Pin 2 stays on while pin 5 is added — exactly the "touch only one bit" guarantee |= gives you.
Try it: setting multiple bits at once with one mask
Combining several single-bit masks with OR before the |= lets you set multiple unrelated bits in one step, still without disturbing any other bit.
Test what you just read
1. What operator/pattern sets bit N to 1 without affecting other bits?
OR-ing in a single-bit mask forces that bit to 1 while leaving every other bit exactly as it was.