Learn C++
#include "operators/op_bitwise.hpp"

Bitwise Operators in C++

//concept

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.

//how it works
1

&, |, ^, ~

AND keeps shared 1-bits, OR merges them, XOR flags differences, NOT inverts — each operates per bit position independently.

2

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.

3

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.

4

Stick to unsigned

Bit manipulation on signed ints invites undefined and implementation-defined behavior — unsigned int (or uint32_t) is the safe default.

//example
#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;
}
Output
3
1
8
1OR-ing in bit 0 (READ) then bit 1 (WRITE) builds the bit pattern 11 binary = 3.
2flags & READ masks everything but bit 0, yielding 1 (nonzero = the flag is set).
31u << 3 shifts a 1-bit left three places to binary 1000 = 8.
//use cases
Packing permission and option flags into a single integer
Parsing binary protocols and file headers field by field
Fast power-of-two scaling and alignment math with shifts
XOR tricks like in-place swap and finding a lone duplicate (a ^ a == 0)

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.