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): they return flags with that bit set to 1 or cleared to 0, and every other bit unchanged. 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. Setting a bit that is already set, or clearing one that is already clear, returns flags unchanged.