What the shift operators do
<< shifts the bits of a value to the left, and >> shifts them to the right. In x << n, every bit moves n positions to the left, and the empty positions on the right fill with 0. In x >> n, bits move n positions to the right, and bits that fall off the right end are dropped. For unsigned values, the empty positions on the left fill with 0.
The shift operator in C is simple to use, but it has a few traps, covered below.
Take 5, which is binary 101:
5 << 1is1010, which is 10.5 << 2is10100, which is 20.5 >> 1is10, which is 2. The last 1 falls off the end.
For unsigned values, each left shift by one position doubles the value, as long as the result still fits in the type. Each right shift by one divides by two and discards the remainder.
A C example
This example uses printf and // comments, so it works in both C and C++.
#include <stdio.h>
int main(void) {
unsigned int x = 5; // binary 101
printf("%u << 1 = %u\n", x, x << 1); // 10
printf("%u << 2 = %u\n", x, x << 2); // 20
printf("%u >> 1 = %u\n", x, x >> 1); // 2
return 0;
}
Output:
5 << 1 = 10
5 << 2 = 20
5 >> 1 = 2
Building bit masks
1u << k produces a value with only bit k set. The u suffix makes the constant unsigned, which keeps the shift away from the sign bit. Combined with |, & and ~, a mask lets you set, clear and read a single bit:
unsigned int flags = 0;
flags |= 1u << 3; // set bit 3, flags is 8
int is_set = (flags >> 3) & 1; // read bit 3, is_set is 1
flags &= ~(1u << 3); // clear bit 3, flags is 0
Shifts and multiplication
For unsigned values that do not overflow, x << n gives the same result as x * 2^n. Compilers already optimize multiplication by a power of two, so use shifts when you are working with bit positions, not to speed up arithmetic.
Operator precedence
Shift operators bind less tightly than + and -. So 1 << n + 1 means 1 << (n + 1). When you mix them, add parentheses: (1 << n) + 1.
Shift count and overflow rules
Three rules keep shifts safe:
- The shift count must not be negative, and it must be smaller than the number of bits in the left operand’s type, after promotion. Otherwise the behavior is undefined.
- Shifting a 1 into the sign bit of a signed
int, as in1 << 31, can be undefined behavior in C, depending on the standard version. Use1u << 31instead. - Right shifting a negative signed value is implementation-defined. Stick to unsigned types when the bit pattern matters.
Summary
<< moves bits left and >> moves them right. Use 1u << k to build masks, keep shift counts in range, and prefer unsigned types when the bit pattern matters.