0
0
Cprogramming~5 mins

Left shift and right shift in C

Choose your learning style9 modes available
Introduction

Left shift and right shift move the bits of a number left or right. This helps multiply or divide numbers quickly by powers of two.

When you want to multiply a number by 2, 4, 8, etc., quickly.
When you want to divide a number by 2, 4, 8, etc., quickly (for positive numbers).
When you need to manipulate individual bits in low-level programming.
When optimizing code for speed in embedded systems or games.
Syntax
C
value << n;  // shifts bits of value to the left by n places
value >> n;  // shifts bits of value to the right by n places

Left shift (<<) moves bits to the left, adding zeros on the right.

Right shift (>>) moves bits to the right, discarding bits on the right.

Examples
Shifting 3 left by 2 bits multiplies it by 4.
C
int x = 3; // binary 00000011
int y = x << 2; // shifts left by 2 bits
// y is now 12 (00001100)
Shifting 16 right by 3 bits divides it by 8.
C
int x = 16; // binary 00010000
int y = x >> 3; // shifts right by 3 bits
// y is now 2 (00000010)
Sample Program

This program shows how shifting left multiplies by 2 and shifting right divides by 2.

C
#include <stdio.h>

int main() {
    int a = 5; // binary 00000101
    int left_shift = a << 1; // multiply by 2
    int right_shift = a >> 1; // divide by 2

    printf("Original value: %d\n", a);
    printf("After left shift by 1: %d\n", left_shift);
    printf("After right shift by 1: %d\n", right_shift);

    return 0;
}
OutputSuccess
Important Notes

Right shifting negative numbers may behave differently depending on the system (arithmetic vs logical shift).

Shifting by more bits than the size of the data type can cause undefined behavior.

Summary

Left shift (<<) moves bits left, multiplying by powers of two.

Right shift (>>) moves bits right, dividing by powers of two for positive numbers.

Useful for fast math and bit-level operations.