Codele / Algorithms
Bit tricks
A number is a row of switches. Bit tricks work on those switches directly, which is very fast and lets you do clever things in one step.
- A number is a row of bits, switches that are on (1) or off (0). Bit tricks work on the switches directly.
- AND gives 1 only if both bits are 1. OR gives 1 if either is 1. XOR gives 1 if the bits are different.
- Shifting left by 1 slides every bit one column left, which doubles the number. Shifting right halves it, dropping the remainder.
- A number AND 1 looks only at the last switch, so it tells you whether the number is odd (1) or even (0).
- In code: & is AND, | is OR, ^ is XOR, << shifts left and >> shifts right.
Loading the playable lesson…