Bitwise Operators in C++
Bitwise operators (&, |, ^, ~, <<, >>) manipulate individual bits of integers — the language of flags, masks, protocols, and performance tricks. & keeps only bits set in both operands, | keeps bits set in either, ^ keeps bits set in exactly one, and ~ flips every bit. Shifts move bit patterns left (multiply by powers of two) or right (divide).
Use unsigned types for bit work: right-shifting negative signed values is implementation-defined, and << overflowing into the sign bit is undefined behavior. Compound forms (&=, |=, <<=) make flag updates one-liners.
&, |, ^, ~
AND keeps shared 1-bits, OR merges them, XOR flags differences, NOT inverts — each operates per bit position independently.
Shifts << and >>
x << 2 multiplies by 4, x >> 2 divides by 4 (for non-negative values) — historically faster than arithmetic, always exact for powers of two.
Flags and masks
Test a flag with (perms & READ), set one with perms |= WRITE, clear with perms &= ~EXEC — three idioms covering nearly all flag code.
Stick to unsigned
Bit manipulation on signed ints invites undefined and implementation-defined behavior — unsigned int (or uint32_t) is the safe default.
#include <iostream> int main() { unsigned int flags = 0; const unsigned int READ = 1, WRITE = 2; flags |= READ; flags |= WRITE; std::cout << flags << std::endl; std::cout << (flags & READ) << std::endl; std::cout << (1u << 3) << std::endl; 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.