C Programming: Memory, Pointers and the Stack ยท Structs and Types

Bitwise Operators and Flags

Store several on/off flags in one int: turn bits on with |, test with &, turn off with & ~, and shift.

bitwise.c

#include <stdio.h>

#define FLAG_READ  1      /* 001 */
#define FLAG_WRITE 2      /* 010 */
#define FLAG_EXEC  4      /* 100 */

int main(void) {
    int perms = 0;
    perms = perms | FLAG_READ;            /* turn a bit on */
    perms = perms | FLAG_EXEC;
    int can_write = (perms & FLAG_WRITE) != 0;
    perms = perms & ~FLAG_EXEC;           /* turn a bit off */
    int shifted = 1 << 4;                 /* 16 */
    int toggled = 6 ^ 3;                  /* 110 ^ 011 = 101 */
    printf("%d %d %d %d\n", perms, can_write, shifted, toggled);
    return 0;
}

Step by step

  1. perms is created on the stack with the value 0.
  2. perms | 1 turns bit 0 on: 001.
  3. Bit 2 on as well: 101 = 5.
  4. perms & 2 tests bit 1: it is off.
  5. & ~4 clears bit 2: back to 001.
  6. 1 << 4 shifts left 4 places: 16.
  7. toggled is created on the stack with the value 5.
  8. It prints 1 0 16 5.
  9. The method returns 0.
  10. 1 0 16 5.