What are the shift operations in C language?

Shift operations in C are bitwise operators that move bits of a number left or right. These operations are fundamental for bit manipulation and can be used for efficient multiplication and division by powers of 2.

Syntax

variable << n    // Left shift by n positions
variable >> n    // Right shift by n positions
~variable        // Bitwise complement (NOT operation)

Left Shift Operation

The left shift operator (<<) moves bits to the left by specified positions. Each left shift by one position doubles the value.

Original: 9 (binary: 1001) 0 0 1 0 1 Left shift by 1: 18 (binary: 10010) 0 1 0 1 0

Right Shift Operation

The right shift operator (>>) moves bits to the right by specified positions. Each right shift by one position halves the value (for positive numbers).

Original: 9 (binary: 1001) 0 0 1 0 1 Right shift by 1: 4 (binary: 0100) 0 0 0 1 0

Example: Shift Operations and Complement

The following program demonstrates left shift, right shift, and bitwise complement operations −

#include <stdio.h>

int main() {
    int a = 9;
    
    printf("Original value of a = %d<br>", a);
    printf("Right shift of a = %d<br>", a >> 1);
    printf("Left shift of a = %d<br>", a << 1);
    printf("Complement of a = %d<br>", ~a);
    printf("Right shift by 2 of a = %d<br>", a >> 2);
    printf("Left shift by 2 of a = %d<br>", a << 2);
    
    return 0;
}
Original value of a = 9
Right shift of a = 4
Left shift of a = 18
Complement of a = -10
Right shift by 2 of a = 2
Left shift by 2 of a = 36

Key Points

  • Left shift by n positions multiplies the number by 2^n
  • Right shift by n positions divides the number by 2^n (integer division)
  • Bitwise complement (~) flips all bits, resulting in -(n+1) for positive number n
  • Shift operations are faster than multiplication/division for powers of 2

Conclusion

Shift operations provide efficient ways to multiply and divide by powers of 2. Understanding these bitwise operations is essential for low-level programming and optimization in C.

Updated on: 2026-03-15T13:17:55+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements