basics · beginner · ~10 min

Set a single bit

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

Challenge

Turn on one specific bit of a 32-bit value, leaving all the others as they were.

Task

Implement unsigned set_bit(unsigned x, int n) that returns a copy of x with bit n set to 1. Bits are numbered from 0 (the least-significant bit). The input is not modified in place.

Input

An unsigned value x (32-bit) and a bit index n in the range 0..31.

Output

Returns x with bit n forced to 1; every other bit keeps its original value.

Example

set_bit(0x0, 0)    ->   0x1     (binary 0000 -> 0001)
set_bit(0x8, 0)    ->   0x9     (binary 1000 -> 1001)
set_bit(0xF, 2)    ->   0xF     (bit already 1: no change)
set_bit(0x0, 31)   ->   0x80000000

Edge cases

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

Rules

  • No loops — one shift-and-OR expression suffices.

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

An unsigned 32-bit value x and a bit index n in 0..31.

Output format

x with bit n set to 1; other bits unchanged.

Constraints

No loops; a single expression is preferred. Shift 1u (unsigned), not 1.

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.