← Exercises|

Set, clear, toggle, test

Write5 of 14 · about 8 min

Set, clear, toggle, test

A single integer can hold 32 independent yes/no answers, one per bit. Device drivers, file permissions and network protocol headers are all built this way, and the four operations you need are always the same.

To make a mask for bit n, shift 1 left n times: 1u << n. Then: set with |=, clear with &= ~mask, toggle with ^=, and test with &.

Use an unsigned type. Shifting bits off the top of a signed integer is undefined behaviour, and shifting a signed value right is implementation-defined.

Example

unsigned int flags = 0;
flags |= (1u << 2);          /* set bit 2   -> 0b100 */
flags &= ~(1u << 2);         /* clear bit 2 -> 0b000 */
flags ^= (1u << 0);          /* toggle bit 0 -> 0b001 */
int on = (flags >> 0) & 1u;  /* test bit 0  -> 1 */

Bit 0 is the rightmost bit, worth 1. Bit 3 is worth 8.

Your task

Write the four functions below. set_bit, clear_bit and toggle_bit each return the changed value; test_bit returns 1 or 0. main is written for you.

Stuck?

Explain it

Why does return value & (1u << n); fail as a test_bit?

Not graded — this is for you.

Where this goes

Project 3 builds these four patterns into a small library and uses them on a made-up device register. These are the exact functions it asks for.