Bitwise Operations

Lesson 16 of 20

Flip, mask and shift the 1s and 0s inside an int — the operators that talk directly to the hardware.

The big picture

Numbers are bits

Every int is 32 bits of 0s and 1s — bitwise operators let you edit those bits directly and in parallel.

Numbers are bits

5 is binary 101; 6 is 110. Bitwise operators work on those columns all at once.

&, | and ^

AND keeps bits where both are 1; OR where at least one is; XOR where they differ.

Shifts move bits

x << n slides bits left (multiplying by 2 each step); x >> n slides them right.

Masks test bits

ANDing with a mask like 1 (binary 001) checks whether one specific bit is switched on.