Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
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).
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.
