Bitwise Operators in C
Bitwise operators (&, |, ^, ~, <<, >>) manipulate individual bits — the language of flags, masks, protocols, and drivers. & keeps only bits set in both operands, | keeps bits set in either, ^ keeps bits set in exactly one, and ~ flips every bit. Shifts move patterns left (multiply by powers of two) or right (divide).
Use unsigned types for bit work: right-shifting negatives and left-shifting into the sign bit are undefined or implementation-defined. Compound forms (&=, |=, <<=) make flag updates one-liners, and C's bit operators (unlike logical ones) never short-circuit.
&, |, ^, ~
AND keeps shared 1-bits, OR merges them, XOR flags differences, NOT inverts — each per bit position independently.
Shifts << and >>
x << 2 multiplies by 4, x >> 2 divides by 4 (for non-negative values) — exact power-of-two scaling.
Flags and masks
Test with (perms & READ), set with perms |= WRITE, clear with perms &= ~EXEC — three idioms covering nearly all flag code.
Stick to unsigned
Bit manipulation on signed ints invites undefined behavior — unsigned int (or uint32_t) is the safe default.
#include <stdio.h> int main(void) { unsigned int flags = 0; unsigned int READ = 1, WRITE = 2; flags |= READ; flags |= WRITE; printf("%u\n", flags); printf("%u\n", flags & READ); printf("%u\n", 1u << 3); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.