Home / Learn Embedded C / Setting a Bit

Setting a Bit

Turning on exactly one bit without disturbing any of the others.

The gistTurning on exactly one bit without disturbing any of the others.

The idea, explained simply

Setting bit 2 of 0b00000000start: 0b00000000mask = 1 << 2 =0b00000100value |= maskresult: 0b00000100
Setting bit 2 of 0b00000000

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

Setting individual pins on an 8-bit portC: edit and run

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

Enabling three interrupt sources in a single ORC: edit and run

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?