Bitwise operators manipulate individual bits—essential for flags, embedded registers, codecs, and low-level protocols.
Operators
&— AND|— OR^— XOR<<,>>— shifts~— NOT
Mask example
#define FLAG_READY (1u << 0)
unsigned flags = FLAG_READY;
if (flags & FLAG_READY) { /* set */ }
Use unsigned types for portable shift behavior. Shifting past width is UB.
Important interview questions and answers
- Q: Set bit n?
A:x |= (1u << n) - Q: Clear bit n?
A:x &= ~(1u << n) - Q: Logical vs arithmetic shift?
A: Right shift of signed negative values is implementation-defined in C—prefer unsigned for portable bit tricks.
Self-check
- What is 5 & 3?
- How do you test if bit 2 is set?
Interview prep
- Set bit n?
flags |= (1u << n);— use unsigned types for portable shift behavior.