Bitwise Operations in C

Level 5214 keystrokes

Sets bits 0 and 2 of an unsigned int with |= and shifted masks, so flags becomes 5 (binary 101). It then reads each bit back with >> and & 1, printing 1, 0 and 1 for bits 0, 1 and 2.

C code

// Starts with every bit cleared
1unsigned int flags = 0;
// 1 << 0 is the mask 001; OR-ing it sets bit 0 (flags = 1)
2flags |= (1 << 0);
// 1 << 2 is the mask 100; now bits 0 and 2 are set (binary 101 = 5)
3flags |= (1 << 2);
// Prints flags: 5; %u is the format for unsigned int
4printf("flags: %u\n", flags);
// Shifts bit 0 to the right end and keeps only it with & 1: prints 1
5printf("bit 0: %d\n", (flags >> 0) & 1);
// Bit 1 was never set: prints 0
6printf("bit 1: %d\n", (flags >> 1) & 1);
// Bit 2 is set: prints 1
7printf("bit 2: %d\n", (flags >> 2) & 1);

Output

flags: 5
bit 0: 1
bit 1: 0
bit 2: 1
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.

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

More C examples at level 5

← C typing practice