How to Use Left Shift Operator in C: Syntax and Examples
In C, the left shift operator
<< shifts the bits of an integer to the left by a specified number of positions, effectively multiplying the number by 2 for each shift. Use it as value << number_of_positions to move bits left and fill with zeros on the right.Syntax
The left shift operator in C is written as <<. It takes two operands: the value to shift and the number of bit positions to shift.
- value: An integer whose bits you want to shift.
- number_of_positions: How many bits to move to the left.
The bits shifted out on the left are discarded, and zeros fill in from the right.
c
result = value << number_of_positions;
Example
This example shows how left shifting a number by 1 doubles it, and shifting by 3 multiplies it by 8.
c
#include <stdio.h> int main() { int value = 5; // binary 00000101 int shifted1 = value << 1; // shift left by 1 bit int shifted3 = value << 3; // shift left by 3 bits printf("Original value: %d\n", value); printf("Value << 1: %d\n", shifted1); printf("Value << 3: %d\n", shifted3); return 0; }
Output
Original value: 5
Value << 1: 10
Value << 3: 40
Common Pitfalls
Common mistakes when using left shift in C include:
- Shifting by a number greater or equal to the bit width of the type (e.g., 32 or more for 32-bit int) causes undefined behavior.
- Using left shift on negative numbers can lead to unexpected results because of how signed integers are stored.
- Assuming left shift always multiplies by powers of two without considering overflow.
c
#include <stdio.h> int main() { int x = 1; // Wrong: shifting by 32 on a 32-bit int is undefined // int y = x << 32; // Correct: shift less than bit width int z = x << 4; // shifts by 4 bits printf("Shifted by 4: %d\n", z); return 0; }
Output
Shifted by 4: 16
Quick Reference
| Operation | Description | Example |
|---|---|---|
| value << n | Shift bits of value left by n positions | 5 << 1 = 10 (5 * 2) |
| Bits shifted out | Discarded from left | N/A |
| New bits | Filled with zeros on right | N/A |
| Shift limit | Must be less than bit width | int: 0 to 31 on 32-bit system |
| Effect on negative | May cause undefined or unexpected results | Avoid shifting negative numbers |
Key Takeaways
Use
<< to shift bits left, multiplying by 2 for each shift.Never shift by a number equal or larger than the bit width of the type to avoid undefined behavior.
Left shifting negative numbers can cause unexpected results; use with caution.
Bits shifted out on the left are lost; zeros fill in from the right.
Left shift is a fast way to multiply by powers of two but watch for overflow.