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:
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 1toggles 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).
// 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).