basics · beginner · ~10 min

Set a single bit

Compose `OR` with a 1-shifted mask to set a specific bit.

Challenge

Implement unsigned set_bit(unsigned x, int n) that returns x with bit n set to 1 (other bits unchanged).

  • Bits are indexed from 0 (least-significant).
  • 0 <= n < 32.
  • The function must not modify its inputs in place.

Examples

set_bit(0b0000, 0) -> 0b0001
set_bit(0b1000, 0) -> 0b1001
set_bit(0b1111, 2) -> 0b1111   // already 1; no-op semantically

Edge cases

  • n == 0 sets the least-significant bit.
  • n == 31 sets the sign bit when reinterpreted as int.
  • Setting a bit that is already 1 returns x unchanged.

Why this matters

Every flag word in C is a bag of bits. Setting bit n of a register is the most basic operation in hardware drivers, IP-header construction, and bitmask data structures. Internalising this idiom unlocks the rest of bit twiddling.

Input format

x is an unsigned 32-bit value; n is 0..31.

Output format

The new word.

Constraints

No loops. Single expression preferred.

Starter code

unsigned set_bit(unsigned x, int n) { /* TODO */ return x; }

Common mistakes

Shifting 1 (signed int) — undefined for n == 31. Use 1u. Returning x | n instead of x | (1u << n).

Edge cases to handle

n == 0; n == 31; bit already set.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.