C Programming • C17 baseline, standards-specific features labeled
Bitwise Operators and Flags
Use bitwise operations for compact flags and masks, with unsigned values and clearly named bits.
Bitwise operators act on individual bits of integer values. They are useful in device registers, binary formats, and permission masks, but are not substitutes for ordinary logical operators. Use unsigned values for bit manipulation and parenthesize masks so the intent is clear.
Example
#include <stdio.h>
enum permission {
PERMISSION_READ = 1u << 0,
PERMISSION_WRITE = 1u << 1
};
int main(void) {
unsigned granted = PERMISSION_READ | PERMISSION_WRITE;
if ((granted & PERMISSION_WRITE) != 0u) {
puts("write allowed");
}
return 0;
}
What to expect
write allowed
Key idea: Name each bit and use masks deliberately; shifting by an invalid count or shifting signed values can produce undefined behavior.