C bit manipulation and flags

Bitwise operators work on the individual bits of integers. A flag is one bit with a name, defined as a shifted constant such as 1u << 2. OR sets a flag, AND with the complement clears it, XOR toggles it, and AND tests it. Packing several yes/no options into one integer is common in file permissions, hardware registers, and network protocols.

C
#include <stdint.h>
#include <stdio.h>

#define FLAG_READ (1u << 0)
#define FLAG_WRITE (1u << 1)
#define FLAG_EXEC (1u << 2)

static int popcount(uint32_t x) {
  int count = 0;
  while (x != 0) {
    x &= x - 1;
    count++;
  }
  return count;
}

static int is_power_of_two(uint32_t x) {
  return x != 0 && (x & (x - 1)) == 0;
}

int main(void) {
  unsigned perms = FLAG_READ | FLAG_WRITE;
  printf("can write: %d\n", (perms & FLAG_WRITE) != 0);
  perms |= FLAG_EXEC;
  perms &= ~FLAG_WRITE;
  perms ^= FLAG_READ;
  printf("perms: %u\n", perms);
  printf("popcount(255) = %d, popcount(1024) = %d\n", popcount(255), popcount(1024));
  printf("64 is a power of two: %d, 66: %d\n", is_power_of_two(64), is_power_of_two(66));

  int a = 5, b = 9;
  a ^= b;
  b ^= a;
  a ^= b;
  printf("swapped: a=%d b=%d\n", a, b);
  return 0;
}
Read the full lesson