Skip to main content

Section 1.5 Reference: Bit Twiddling

The operations used in Blinky, setting and clearing individual bits without disturbing the rest of a register, appear in virtually every line of embedded-systems code. Collectively they are called bit twiddling. They rely on three bitwise operators whose behavior on each pair of bits is captured in these truth tables:
Bitwise OR ( | )
A B A | B
0 0 0
0 1 1
1 0 1
1 1 1
Bitwise AND ( & )
A B A & B
0 0 0
0 1 0
1 0 0
1 1 1
Bitwise XOR ( ^ )
A B A ^ B
0 0 0
0 1 1
1 0 1
1 1 0
These are the facts register programming rests on: OR with 1 forces a bit to 1; OR with 0 leaves it unchanged. AND with 0 forces a bit to 0; AND with 1 leaves it unchanged. XOR with 1 toggles a bit (flips 0→1 or 1→0); XOR with 0 leaves it unchanged. The three fundamental patterns are:
// Set bit n in register NUM (force that bit to 1):
NUM |= (1U << n);

// Clear bit n in register NUM (force that bit to 0):
NUM &= ~(1U << n);

// Toggle bit n in register NUM (flip 0→1 or 1→0):
NUM ^= (1U << n);
The expression (1U << n) is called a bit mask: it has exactly one 1 bit (at position \(n\)) and zeros everywhere else. The U suffix makes it an unsigned 32-bit integer, which is important when \(n\) equals 31 (shifting into the sign bit of a signed int would cause undefined behavior in C).
Two additional idioms let you test whether a bit is set without modifying the register:
// Test if bit n is 0:
if ((NUM & (1U << n)) == 0)  { /* bit n is 0 */ }

// Test if bit n is 1 (non-zero):
if ((NUM & (1U << n)) != 0)  { /* bit n is 1 */ }
AND-ing a register with a one-bit mask zeroes every bit except the one we care about. The result is either 0 (bit was 0) or a non-zero value (bit was 1).

Check Your Understanding Check Your Understanding

1.

Suppose NUM = 0b00101101 (8-bit example). What is the value of NUM after NUM ^= (1U << 5)?
  • 0b00001101
  • Correct. Bit 5 in 0b00101101 is already 1; XOR with 1 toggles it to 0, giving 0b00001101.
  • 0b00101101 (unchanged)
  • XOR with 1 always flips the bit; it does not leave it unchanged.
  • 0b00111101
  • This would result from setting bit 4. Verify: (1U<<5) = 0b00100000.
  • 0b10101101
  • Check the mask position: (1U<<5) sets bit 5, which is 0b00100000, not bit 7.

2.

Write the single C statement that clears bit 3 in a 32-bit register named REG without changing any other bit.