Avatar ·

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

Hello everyone! I'm a beginner C++ developer and I've encountered a problem when working with bits. I need to manage individual bits in an integer, but I can't understand how to do it correctly.

\n\n

I have a variable uint8_t flags = 0b00000000;. I want to:

\n
    \n
  • Set the 3rd bit (make it 1)
  • \n
  • Clear the 5th bit (make it 0)
  • \n
  • Toggle the 2nd bit (invert its value)
  • \n
\n\n

I tried to write this code:

\n\n
uint8_t flags = 0b00000000;\n// Set the 3rd bit\nflags = flags | 3;  // But this doesn't work\n// Clear the 5th bit\nflags = flags & 5;  // Also not right\n// Toggle the 2nd bit\nflags = flags ^ 2;  // Seems to work, but I'm not sure
\n\n

The problem is that I don't understand how to correctly specify