typestar

Bit flags in C

Setting, clearing, and testing individual bits.

unsigned set_bit(unsigned flags, int pos) {
    return flags | (1u << pos);
}

unsigned clear_bit(unsigned flags, int pos) {
    return flags & ~(1u << pos);
}

int test_bit(unsigned flags, int pos) {
    return (flags >> pos) & 1u;
}

How it works

  1. 1u << pos builds a mask for one bit.
  2. | sets, & ~ clears that bit.
  3. Shifting then & 1u tests it.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
222
Tokens
64
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 38 seconds.

Type this snippet

Step 1 of 2 in Bit manipulation, step 17 of 20 in Data structures & algorithms.

← Previous Next →