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

Logical vs Arithmetic shifts

Logical vs Arithmetic shifts

What you'll learn: The difference between how C handles shifting bits for unsigned numbers versus signed numbers.

In the previous lesson, we looked at how >> moves bits to the right. However, there is a catch: when we move bits out, we leave empty spaces behind. C fills these gaps differently depending on whether the number is "signed" (can be negative) or "unsigned."

The Logical Shift (Filling with Zeros)

A logical shift is straightforward. Imagine a row of people sitting on a bench. If everyone moves one seat to the right, the person at the far end falls off, and the new seat at the beginning is filled by a "neutral" person (a zero).

In C, unsigned integers always use logical shifts. When you shift right, the computer always pulls in 0s from the left.

The Arithmetic Shift (Preserving the Sign)

Signed integers are trickier because the very first bit (the most significant bit) represents whether the number is positive or negative. If we simply shifted in a 0 to a negative number, the "negative" marker would disappear, and our negative number would suddenly become a huge positive number!

To prevent this, C often uses an arithmetic shift for signed integers. Instead of filling the empty gap with a 0, it "smears" the sign bit. If the number was negative (starts with 1), it fills the new gaps with 1s. If it was positive (starts with 0), it fills them with 0s.

Code Example

Think of it as a safety feature for math. A right shift is equivalent to dividing by two; an arithmetic shift ensures that -10 divided by 2 stays negative.

#include <stdio.h>

int main() {
    // Logical Shift: Always fills with 0
    unsigned int a = 8;     // Binary: 00001000
    unsigned int b = a >> 1; // Result: 00000100 (4)

    // Arithmetic Shift: Fills with the sign bit
    signed int x = -8;      // Binary starts with 1...
    signed int y = x >> 1;  // Result starts with 1... (-4)
    
    return 0;
}

While the C standard allows some flexibility, most modern compilers treat signed right-shifts as arithmetic to keep your math consistent.

Key takeaway

Logical shifts always fill gaps with 0, while arithmetic shifts copy the sign bit to preserve the number's positive or negative status.