Toggle Bit in C

Level 4236 keystrokes

Uses XOR to toggle a specific bit at a given position in an integer.

C code

// Function to toggle bit at position pos
1unsigned int toggle(unsigned int n, int pos) {
// XOR with 1 at position flips that bit
2 return n ^ (1 << pos);
3}
4
// 0b binary literal (C23, earlier a GCC/Clang extension): 1010 = 10
5unsigned int val = 0b1010;
// Print original value
6printf("Original: %u\n", val);
// Toggle bit 0: 1010 -> 1011 = 11
7val = toggle(val, 0);
8printf("Toggle 0: %u\n", val);
// Toggle bit 1: 1011 -> 1001 = 9
9val = toggle(val, 1);
10printf("Toggle 1: %u\n", val);

Output

Original: 10
Toggle 0: 11
Toggle 1: 9
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
  • )× 7
  • ,× 6
  • "× 6
  • :× 3
  • \× 3
  • %× 3
  • =× 3
  • <× 2

More C examples at level 4

← C typing practice