Bit Manipulation in C

Level 4173 keystrokes

Demonstrates setting and checking individual bits using bitwise operators.

C code

// Start with all bits clear
1unsigned int flags = 0;
// Set bit 0 using OR with left shift
2flags |= (1 << 0);
// Set bit 2 (flags is now 0101 = 5)
3flags |= (1 << 2);
// Print flags value (5)
4printf("Flags: %u\n", flags);
// Check bit 0: shift right and mask with 1
5printf("Bit 0: %d\n", (flags >> 0) & 1);
// Check bit 1 (not set, so 0)
6printf("Bit 1: %d\n", (flags >> 1) & 1);

Output

Flags: 5
Bit 0: 1
Bit 1: 0
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C code and how often they appear.

  • (× 7
  • )× 7
  • ;× 6
  • "× 6
  • <× 4
  • >× 4
  • ,× 3
  • :× 3
  • \× 3
  • %× 3

More C examples at level 4

← C typing practice