Sobes.tech
Junior — Senior

Changing the value of a bit in a number at a specified position

livecode

Task condition

Task: implement the set_bit function, which takes a 32-bit unsigned number num, a bit position pos (zero-indexed), and a boolean value. The function should return a new number where the bit at position pos is set to 1 if value is true, otherwise to 0.

std::uint32_t set_bit(std::uint32_t num, std::uint32_t pos, bool value) {
    // implement
}

Example:

num = 5 (0101b), pos = 1, value = false → result 1 (0001b)
num = 5 (0101b), pos = 2, value = true  → result 5 (0101b)