Avatar ·

How to set, clear, and toggle a single bit in C++?

Hi! I'm writing a program for a microcontroller in C++ and working with registers. I need to control individual bits: set them to 1, clear them to 0, and toggle (invert) them. I know this is done using bitwise operations, but I keep getting confused with the syntax. For example, I have a variable `uint8_t flags = 0b00001111;`. I want to: 1. Set bit 3 (counting from zero) to 1. 2. Clear bit 2 to 0. 3. Toggle bit 1 (if 1 → 0, if 0 → 1). Currently I'm doing it like this: ```cpp uint8_t flags = 0b00001111; // Set bit 3 flags = flags | 0b00001000; // Works, but inconvenient // Clear bit 2 flags = flags & 0b11111011; // I keep making mistakes with the mask // Toggle bit 1 flags = flags ^ 0b00000010; // Seems to work ``` Questions: - Are there any commonly accepted