In 1 << n, the number 1 is shifted left by n bit positions. The result is 2 raised to the power of n: 1 << 0 is 1, 1 << 1 is 2, 1 << 2 is 4, and 1 << 3 is 8. The << operator moves every bit up by n places and fills the empty places on the right with zeros. The number 1 has only one bit set, at position 0, so after the shift that single bit sits at position n.
Reading it in binary
Positions are numbered from 0 at the right end. Here are a few shifts of 1, written as 8-bit patterns:
| Expression | Binary (8 bits) | Value |
|---|---|---|
1 << 0 |
00000001 |
1 |
1 << 1 |
00000010 |
2 |
1 << 2 |
00000100 |
4 |
1 << 3 |
00001000 |
8 |
1 << 4 |
00010000 |
16 |
An int has more than eight bits, but the extra bits at the top are all zero, so the pattern is the same.
A small program
#include <stdio.h>
int main(void) {
for (int n = 0; n <= 4; n++) {
printf("1 << %d = %d\n", n, 1 << n);
}
return 0;
}
The program prints:
1 << 0 = 1
1 << 1 = 2
1 << 2 = 4
1 << 3 = 8
1 << 4 = 16
The declaration inside for needs C99 or later, or C++.
Using 1 << n as a bit mask
Because 1 << n has exactly one bit set, it works as a mask that picks out bit n. Setting, testing, and clearing a single bit are the most common uses. The 1u suffix makes the constant unsigned, which keeps the bit operations free of sign problems.
#include <stdio.h>
int main(void) {
unsigned int flags = 0;
int n = 2;
flags |= (1u << n); /* set bit n */
printf("flags = %u\n", flags);
if (flags & (1u << n)) { /* test bit n */
printf("bit %d is set\n", n);
}
flags &= ~(1u << n); /* clear bit n */
printf("flags = %u\n", flags);
return 0;
}
Output:
flags = 4
bit 2 is set
flags = 0
How large n can be
The result equals 2 to the power of n only when that value fits in the type. Is int 2 or 4 bytes in C? That depends on the platform. On a platform where int is 32 bits:
nfrom 0 to 30 gives a positiveint. For example,1 << 30is 1073741824.1 << 31sets the sign bit of a 32-bitint. In C, and in C++ before C++20, this is undefined behavior.- Counts of 32 or more, and negative counts, are undefined for a 32-bit
int.
For a wider range, use an unsigned constant or a wider type. 1u << 31 is well defined for a 32-bit unsigned int, and 1LL << 40 is 1099511627776, because long long is at least 64 bits wide. To check the width of int on your platform, use sizeof(int) * CHAR_BIT, with CHAR_BIT from <limits.h>.
Common mistakes
- Missing parentheses.
1 << n + 1means1 << (n + 1). Write(1 << n) + 1when you mean to shift first. - Using a plain 1 for a wide mask.
1 << 40is undefined on a 32-bitint. Use1ULL << 40or1LL << 40instead.