basics · beginner · ~10 min
Compose `OR` with a 1-shifted mask to set a specific bit.
Implement unsigned set_bit(unsigned x, int n) that returns x with bit n set to 1 (other bits unchanged).
0 <= n < 32.set_bit(0b0000, 0) -> 0b0001
set_bit(0b1000, 0) -> 0b1001
set_bit(0b1111, 2) -> 0b1111 // already 1; no-op semantically
n == 0 sets the least-significant bit.n == 31 sets the sign bit when reinterpreted as int.x unchanged.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.
x is an unsigned 32-bit value; n is 0..31.
The new word.
No loops. Single expression preferred.
unsigned set_bit(unsigned x, int n) { /* TODO */ return x; }
Shifting 1 (signed int) — undefined for n == 31. Use 1u. Returning x | n instead of x | (1u << n).
n == 0; n == 31; bit already set.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.