Course contentsShow
← C
Lesson 184 of 1,2193. Operators and ExpressionsFree lesson

Right shift `>>` mechanics

Right shift >> mechanics

What you'll learn: How the right shift operator moves bits to the right and how it acts as a high-speed shortcut for division.

Shifting the patterns

The right shift operator (>>) takes the binary representation of a number and slides all its bits to the right by a specified number of positions. Think of it like a row of people sitting in theater seats. When you "Right Shift 1," everyone stands up and moves one seat to the right. The person at the far end of the row has nowhere to go, so they fall off and are discarded. Meanwhile, an empty seat opens up at the beginning of the row, which is filled with a 0.

In C, the syntax looks like this: result = value >> n; where n is how many seats everyone moves.

A shortcut for math

Beyond just moving bits, the right shift operator has a very practical mathematical use: it performs integer division by powers of two. Because binary is a base-2 system, shifting right by one position is the same as dividing the number by 2 and dropping any remainder. Shifting by two positions is the same as dividing by 4 (222^2), and shifting by three is dividing by 8 (232^3).

Computers can shift bits much faster than they can perform long division, making this a favorite trick for performance-critical code.

The code in action

Here is how the bits move behind the scenes:

#include <stdio.h>

int main() {
    // 20 in binary is 00010100
    unsigned int a = 20; 
    
    // Shift right by 2 positions
    // 00010100 becomes 00000101
    unsigned int result = a >> 2; 
    
    // The result is 5 (which is 20 / 4)
    printf("Result: %u", result);
    
    return 0;
}

Vacancies and sign bits

You might wonder what happens to the "empty seats" created on the left. For unsigned integers (numbers that are always positive), C always fills these spots with 0. However, for signed integers (numbers that can be negative), C usually fills those spots with whatever the sign bit was to preserve the positive or negative nature of the number. This is known as an "arithmetic shift."

Key takeaway

The >> operator slides bits to the right, effectively dividing a number by 2n2^n and discarding the remainder.