# Bitwise Operators & Bit Flags — C Programming Fundamentals: Pointers, Memory and Files

Source: https://www.skillbyai.com/en/c/c-bitwise-operators

> Manipulate individual bits with AND, OR, XOR, NOT and shifts, and pack options into bit flags.

## The six bitwise operators

`&` AND, `|` OR, `^` XOR, `~` NOT (flips every bit), `<<` left shift (multiply by 2 per shift), `>>` right shift (divide by 2 per shift).

## Set, clear, toggle, check a bit

These four patterns cover almost every bit-flag task.

```c
unsigned int flags = 0;

flags |= (1 << 2);   // set bit 2
flags &= ~(1 << 2);  // clear bit 2
flags ^= (1 << 2);   // toggle bit 2

if (flags & (1 << 2)) {
    printf("bit 2 is set\n");
}
```

## Why bit flags?

Packing multiple boolean options into one integer (each bit = one on/off flag) saves memory and is common in embedded systems, permission systems, and hardware registers.

**Quiz:** Which operator flips every bit of a value?

- [ ] ^ (XOR)
- [ ] & (AND)
- [ ] << (left shift)
- [x] ~ (NOT)

*Answer:* ~ (NOT). The bitwise NOT (~) inverts every bit of its operand.
