basics · beginner · ~10 min
Compose `OR` with a 1-shifted mask to set a specific bit.
Turn on one specific bit of a 32-bit value, leaving all the others as they were.
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.
An unsigned value x (32-bit) and a bit index n in the range 0..31.
Returns x with bit n forced to 1; every other bit keeps its original value.
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
n == 0 sets the least-significant bit.n == 31 sets the highest bit (the sign bit when read 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.
An unsigned 32-bit value x and a bit index n in 0..31.
x with bit n set to 1; other bits unchanged.
No loops; a single expression is preferred. Shift 1u (unsigned), not 1.
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.