Course contentsShow
← C
Lesson 1195 of 1,21916. Practice and ProjectsFree lesson

Bitwise operations for speed

Bitwise operations for speed

What you'll learn: How to use low-level bit manipulation to perform common arithmetic operations much faster than standard operators.

Thinking like the processor

Deep inside your computer, everything is a series of 0s and 1s. While the C compiler is very smart, standard arithmetic like multiplication (*) or division (/) can sometimes be "heavy" operations for a CPU.

Imagine you are sorting a massive deck of cards. Using multiplication is like using a calculator every time you need to double a number. Using bitwise operations is like having a physical trick—like sliding every card one slot to the left—to achieve the same result instantly. By manipulating bits directly, you bypass the complex circuitry required for general math.

The power of shifting

The two most common "speed hacks" involve the left shift (<<) and right shift (>>) operators.

In binary, shifting all bits to the left by one position effectively multiplies a number by 2. Shifting to the right divides it by 2. Because these are fundamental "bit-sliding" actions, the CPU can often execute them in a single clock cycle.

#include <stdio.h>

int main() {
    int x = 10; // Binary: 0000 1010

    // Multiplication: x * 4 (which is 2 squared)
    // Shifting left by 2 is much faster than multiplication
    int multi = x << 2; // Result: 40 (Binary: 0010 1000)

    // Division: x / 2
    // Shifting right by 1 is faster than division
    int div = x >> 1;   // Result: 5 (Binary: 0000 0101)

    // Checking if a number is even or odd
    // (x & 1) is faster than (x % 2 == 0)
    if ((x & 1) == 0) {
        printf("%d is even\n", x);
    }

    return 0;
}

When to use this

Modern compilers are excellent at optimizing x * 2 into x << 1 automatically. However, when you are working on performance-critical systems—like graphics engines, embedded microcontrollers, or real-time audio processing—writing bitwise code manually ensures the fastest path is taken.

It also allows for "Bit Masking," where you use the AND operator (&) to check if a specific flag is turned on, which is significantly faster than comparing multiple boolean variables.

Key takeaway

Bitwise operators treat numbers as raw binary strings, allowing for lightning-fast arithmetic and logic by "sliding" or "masking" bits instead of performing heavy mathematical calculations.