0
0
CHow-ToBeginner · 3 min read

How to Use Right Shift Operator in C: Syntax and Examples

In C, the right shift operator >> shifts the bits of an integer to the right by a specified number of positions. It effectively divides the number by powers of two, discarding bits shifted out on the right. Use it as result = value >> number_of_bits;.
📐

Syntax

The right shift operator in C is used as follows:

  • value: an integer whose bits you want to shift.
  • >>: the right shift operator.
  • number_of_bits: how many positions to shift the bits to the right.
  • result: the new integer after shifting.

Shifting right by n bits moves all bits n places to the right, discarding the rightmost bits and filling the left with zeros (for unsigned) or sign bit (for signed).

c
result = value >> number_of_bits;
💻

Example

This example shows how right shifting divides an integer by powers of two:

c
#include <stdio.h>

int main() {
    unsigned int value = 64;  // binary: 01000000
    unsigned int shifted = value >> 3; // shift right by 3 bits

    printf("Original value: %u\n", value);
    printf("After right shift by 3: %u\n", shifted);

    return 0;
}
Output
Original value: 64 After right shift by 3: 8
⚠️

Common Pitfalls

Common mistakes when using right shift in C include:

  • Using right shift on signed integers can cause implementation-defined behavior, especially for negative numbers.
  • Shifting by a number of bits greater or equal to the bit width of the type is undefined behavior.
  • Assuming right shift always divides by powers of two; for signed negative numbers, results may vary.

Always use unsigned integers for predictable right shift results.

c
#include <stdio.h>

int main() {
    int negative = -16;
    unsigned int positive = 16;

    // Right shift on signed negative (may be implementation-defined)
    int shifted_neg = negative >> 2;

    // Right shift on unsigned positive (safe and predictable)
    unsigned int shifted_pos = positive >> 2;

    printf("Signed negative -16 >> 2 = %d\n", shifted_neg);
    printf("Unsigned 16 >> 2 = %u\n", shifted_pos);

    return 0;
}
Output
Signed negative -16 >> 2 = -4 Unsigned 16 >> 2 = 4
📊

Quick Reference

  • Operator: >>
  • Purpose: Shift bits right, dividing by 2n for unsigned.
  • Use unsigned types for predictable results.
  • Shifting signed negatives may vary by compiler.
  • Do not shift by ≥ bit width (e.g., 32 for 32-bit int).

Key Takeaways

Use the right shift operator >> to move bits right and divide unsigned integers by powers of two.
Always prefer unsigned integers for right shifts to avoid unpredictable behavior.
Shifting signed negative numbers can behave differently depending on the compiler.
Never shift by a number of bits equal to or larger than the variable's bit size.
Right shift discards bits on the right and fills left bits with zeros (unsigned) or sign bit (signed).