Exercise · Operators and Expressions · lesson 8 of 8
Exercise: bit flags
A number flags stores a set of flags: flag number bit is on when bit number bit is 1. Write unsigned set_flag(unsigned flags, int bit) and unsigned clear_flag(unsigned flags, int bit): the first returns flags with that bit set to 1, the second with it cleared to 0, and every other bit stays the same. The third function, bool has_flag(unsigned flags, int bit), returns true if that bit is 1.
set_flag(1u, 3)→9uclear_flag(9u, 0)→8uhas_flag(2147483648u, 31)→true
Constraints: bit is from 0 to 31, and an unsigned takes 32 bits. If the bit is already set, set_flag returns flags unchanged; if it is already clear, clear_flag does the same.
Do not add extra #include lines unless the task says so explicitly.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.