Learn C
#include "operators/op_bitwise.h"

Bitwise Operators in C

#concept

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.

#how it works
1

&, |, ^, ~

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

2

Shifts << and >>

x << 2 multiplies by 4, x >> 2 divides by 4 (for non-negative values) — exact power-of-two scaling.

3

Flags and masks

Test with (perms & READ), set 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 behavior — unsigned int (or uint32_t) is the safe default.

#example
#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;
}
Output
3
1
8
1OR-ing in bit 0 then bit 1 builds binary 11 = 3, printed with %u.
2flags & READ masks everything but bit 0, yielding 1 (set).
31u << 3 shifts to binary 1000 = 8.
#use cases
Packing permission and option flags into single integers
Parsing binary protocols and register maps field by field
Fast alignment math ((x + 7) & ~7 rounds up to multiples of 8)
XOR tricks like 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.