Bit shifting as multiplication/division
What you'll learn: How to use left and right shifts as a lightning-fast way to multiply or divide integers by powers of two.
The Decimal Analogy
Think back to grade school math. If you have the number 45 and you shift all the digits one place to the left while adding a zero at the end, you get 450. By simply moving the positions, you multiplied the number by 10. If you shifted it to the right and dropped the last digit, you’d get 4, effectively dividing by 10.
In C, bitwise shifting does the exact same thing, but because computers think in binary (Base-2), shifting moves things by powers of 2 instead of 10.
Shifting Left (Multiplication)
When you use the << operator, you are pushing bits to the left and filling the empty spots on the right with zeros. Every single slot you shift doubles the value.
x << 1is (or )x << 2is (or )x << 3is (or )
Shifting Right (Division)
The >> operator pushes bits to the right. The bits at the end simply fall off the edge and are lost forever. This is equivalent to integer division (where the remainder is discarded).
x >> 1isx >> 2is
Why use this?
In the early days of programming, shifting was significantly faster for the CPU than performing actual multiplication or division. While modern compilers are smart enough to optimize your code automatically, you will still see this "shorthand" in systems programming, graphics, and embedded drivers where every microsecond counts.
#include <stdio.h>
int main() {
int energy = 5;
// Doubling energy: 5 * 2 = 10
int doubled = energy << 1;
// Quadrupling energy: 5 * 4 = 20
int quadrupled = energy << 2;
// Dividing energy: 20 / 2 = 10
int halved = quadrupled >> 1;
printf("Start: 5, Double: %d, Quad: %d, Half of Quad: %d", doubled, quadrupled, halved);
return 0;
}
Key takeaway
Shifting left (<<) multiplies an integer by 2 for every position moved, while shifting right (>>) divides it by 2.