Bit manipulation in C: set, clear, toggle and check
Atlasbot · 16/8/2026 · 10 min read
A 32-bit hardware register typically holds more than just one value — it's an encapsulation Dozens of independent flags and configurations, each bit has its own meaning, to save address space. Reading/writing exactly one bit without affecting the remaining bits requires four basic bit operations that anyone writing embedded code should know by heart.
Key concepts
C provides operators that work directly on each bit of an integer: & (AND), | (OR), ^ (XOR), ~ (NOT/bit inversion), << and >> (shift left/right). Combining them with (1 << n) — a number where only the n bit is 1, the rest are 0 — produces four classic operations:
| Operation | Code | Meaning |
|---|---|---|
| Set bit (on) | REG |= (1 << n) | Set bit n = 1, leave other bits unchanged |
| Clear bit (off) | REG &= ~(1 << n) | Set bit n = 0, leave other bits unchanged |
| Toggle bit (invert) | REG ^= (1 << n) | Invert bit n (0→1 or 1→0) |
| Check bit (check) | if (REG & (1 << n)) | Check bit n is 0 or 1 |
Why can't it be assigned directly?
A common novice mistake is to write REG = (1 << 5); to "enable pin 5" — but this direct assignment clears all other bits to 0, disabling any other configuration enabled in the same register. This is why set/clear operations always use |= and &= combined with the mask, instead of assigning = directly.
In short:
|=to turn on without touching other bits,&= ~(...)to turn off without touching other bits,^=to invert the state,&(not assigned) to only read test. Mistaking one of these four symbols is a very common source of error when configuring registers.
How it works
Example 8-bit configuration register of a hypothetical peripheral, each bit an independent flag:
// Bit 3 = interrupt enabled, other bits remain the same
CONFIG_REG |= (1 << 3);
// Turn off bit 3, does not affect bits 0, 1, 2, 4-7
CONFIG_REG &= ~(1 << 3);
// Check if bit 3 is on or off
if (CONFIG_REG & (1 << 3)) {
// Interrupt is enabled
}
Before: 0 0 0 0 0 0 1 1 (bit 3 is = 0)
Mask: 0 0 0 0 1 0 0 0 (1 << 3)
After OR: 0 0 0 0 1 0 1 1 ← only bit 3 changes to 1, other bits remain the same
This technique appears everywhere in embedded: toggling individual GPIO pins in the mode configuration register, checking the "data ready" flag in the UART status register, or packing multiple boolean values into a single uint8_t instead of using eight separate bool variables — saving RAM when there are hundreds of status flags to monitor.
Technical details
Formulas
In addition to the 4 set/clear/toggle/check operations above, a useful variation is extracts the clean 0/1 value of 1 bit (not just true/false in if, but returns the correct 0 or 1 for further saving/comparison):
Bit value n = (REG >> n) & 1
For example: REG = 0b00001011, need to get bit value 3
(REG >> 3) & 1 = 0b00000001 & 1 = 1
Translating n right first and then ANDing with 1 ensures the result always simplifies to 0 or 1, other than REG & (1 << n) it can return 0 or another number 0 (eg 8 if n=3) — both are "correct" for if, but only this extraction method gives a clean value to assign to variable uint8_t flag = ....
Parameters
Real-life example of bit positions in the UART status register (USART_SR) on STM32 — illustrating why it is necessary to manipulate the correct bits, not read/write the entire register:
| Flag name | Bit position | Meaning |
|---|---|---|
TXE | Bit 7 | The transmit register is empty, ready to receive new bytes |
RXNE | Bit 5 | New bytes received, ready to read |
ORE | Bit 3 | Overrun — new byte arrives before old byte is read |
Practical applications
When a robot has multiple limit switches connected to an 8-bit GPIO port (mentioned in the article Bit/Byte and GPIO), reading the entire port once and then using (REG >> n) & 1 to separate the status of each switch is a much more compact and faster way to handle it than calling digitalRead() 8 times in a row — especially important when you need to know exactly which switch just activated. active in an interrupt that processes the entire port at once, which if reading each pin individually could be missed due to the small delay between reads.
Practical example
#include <stdio.h>
#include <stdint.h>
void print_binary(uint8_t val) {
for (int i = 7; i >= 0; i--) {
printf("%d", (val >> i) & 1);
}
printf("\n");
}
int main() {
uint8_t reg = 0b00000011;
printf("Truoc: "); print_binary(reg);
reg |= (1 << 3); // set bit 3
printf("Sau set(3): "); print_binary(reg);
reg &= ~(1 << 0); // clear bit 0
printf("Sau clear(0): "); print_binary(reg);
printf("Bit 3 = %d\n", (reg >> 3) & 1);
return 0;
}
Output:
Truoc: 00000011
Sau set(3): 00001011
Sau clear(0): 00001010
Bit 3 = 1
The result matches the example in the Operating Principle section — set bit 3 only changes exactly 1 bit, clear bit 0 only turns off bit 0, the remaining bits are not affected by both operations.
Common mistakes
- Forget the parentheses when combining with
==— writeif (REG & (1 << 3) == 1)instead ofif ((REG & (1 << 3)) == 1)— because==has higher precedence than&in C, the expression is calculated in the wrong order completely, always use explicit parentheses when combining bit operators with comparison operators. - Assign
=directly instead of|=/&=— as mentioned in the Main Concepts section, clears any other configurations active in the same register. - Confusing bit numbers between numbering from 0 and numbering from 1 — datasheet always numbers bits starting from 0 (lowest bit), but newbies sometimes mistakenly count "first, second bits" according to everyday habits — always compare correctly according to the bit table in the datasheet, don't guess.
- Bit shift on signed type when not needed — right shift (
>>) on signed number can leave the sign bit intact (arithmetic shift) instead of filling in 0 (logical shift), giving a different result — when manipulating pure bits, always use unsigned type (uint8_t,uint32_t...) to avoid ambiguity.
Conclusion
The four set/clear/toggle/check bit operations, plus the shift-then-AND clean value extraction technique, are the bare minimum toolset for working securely with any hardware register — from configuring the GPIO, to reading UART status flags, to packing multiple flags into a single byte to save RAM. This is also the last article in the C/C++ Programming section — this language foundation will be reused throughout the next Hardware Communication section, where the UART/I2C/SPI status registers are all operated using the same techniques just learned.
Get new articles and lessons by email
When a new technical article or course module is published, Atlas Robotics sends you a short email. No spam.
Unsubscribe any time with the link in each email. See our Privacy policy.