Section 4.20

Shift semantics

Definition

Shift semantics are the exact rules of a bit shift, an operation that moves the bits of an integer a given number of positions, the shift count, to the left or to the right. The rules fix the type of the result, what fills the vacated positions, and which counts and operand values are allowed. In C, the left operand is first promoted, and a negative count, or a count not smaller than the promoted operand’s width in bits, is undefined behavior §4.12. Processors define such counts, but differently.

The idea

A program builds a bit mask §4.50, a value with chosen bits set, covering the low nn bits: mask = (1u << n) - 1. For n=5n = 5, 1u << 5 is 32, binary 100000, and 32−1=3132 - 1 = 31, binary 11111, as intended. For n=32n = 32 the programmer expects all 32 bits set, but C leaves 1u << 32 undefined. On x86 the shift instruction uses only the low 5 bits of the count, so it shifts by 0 and the mask becomes 1−1=01 - 1 = 0. On 32-bit Arm a shift by 32 moves every bit out, giving 0, and the mask becomes 0−10 - 1, which wraps to 0xFFFFFFFF. The same line gives two different masks on two processors, and a compiler that knows nn in advance may produce something else again.

A left shift by kk multiplies by 2k2^k, and a right shift by kk divides by 2k2^k, within a fixed number of bit positions; bits pushed past either end are lost. Because C leaves out-of-range counts undefined, a compiler can translate each C shift into a single shift instruction, whatever that instruction does with such counts. The price is that the programmer must keep every count in range.

How it works

C11, the 2011 edition of the ISO standard that defines the C language, gives the rules for E1 << E2 and E1 >> E2 in section 6.5.7.

  1. Promote each operand separately. Unlike addition, a shift does not bring its operands to a common type; the result has the type of the promoted E1. A uint8_t variable x holding 0x80 is promoted to int, so x << 1 is 256, not 0.

  2. Check the count. Let NN be the width in bits of the promoted E1, for example 32 for a 32-bit int. If E2 is negative, or at least NN, the behavior is undefined.

  3. Left shift. Zeros fill the vacated low bits. For an unsigned E1, the result is E1×2E2E1 \times 2^{E2} reduced modulo 2N2^N: the bits shifted out are lost. For a signed E1, the result is E1×2E2E1 \times 2^{E2} if E1 is not negative and that product fits in the type; otherwise the behavior is undefined. So 1u << 31 is defined, while 1 << 31 with a 32-bit int is undefined, because 2312^{31} exceeds the largest int.

  4. Right shift. For an unsigned E1, or a signed E1 that is not negative, the result is E1/2E2E1 / 2^{E2} rounded down, and zeros fill the vacated high bits: a logical shift. For a negative signed E1, the result is implementation-defined, meaning that each compiler chooses and documents it. GCC §12.17 (the GNU Compiler Collection, from the GNU project, whose name stands for GNU’s Not Unix) and Clang perform an arithmetic shift, which fills the vacated bits with copies of the sign bit.

Processors define every count, but differently:

An interpreter §2.13 or translator that implements such an instruction in C must write the instruction set’s rule explicitly, for example x << (n & 63), instead of relying on the C shift to behave the same way.

Safe practice follows from the rules: do bit manipulation on unsigned types; convert to the final width before shifting, as in (uint32_t)b << 24 for a byte b; and test the count before the shift, handling out-of-range counts on a separate path.

Worked example

Decoding a 4-byte big-endian §4.21 number, one stored most significant byte first. A message holds the bytes 0x80, 0x00, 0x01, 0x00 in a uint8_t array §14.5 p, and the intended value is 0x80000100, which is 231+256=2,147,483,9042^{31} + 256 = 2{,}147{,}483{,}904. The common line p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3] promotes p[0] to a 32-bit int. The first shift then needs 128×224=231=2,147,483,648128 \times 2^{24} = 2^{31} = 2{,}147{,}483{,}648, which exceeds the largest int, 2,147,483,6472{,}147{,}483{,}647, so that shift is undefined. Converting first, (uint32_t)p[0] << 24, makes the shift unsigned: 2,147,483,6482{,}147{,}483{,}648 fits, and the other terms add 0+256+00 + 256 + 0, for a total of 2,147,483,9042{,}147{,}483{,}904.

The mask from the idea, made safe for an unsigned count nn: mask = (n >= 32) ? 0xFFFFFFFFu : (1u << n) - 1u;. For n=5n = 5 it gives 31, and for n=32n = 32 it gives 0xFFFFFFFF on every processor.

Right shifts of negative numbers are not division. With an arithmetic shift, −7-7 is 0xFFFFFFF9 in 32 bits; shifting right by 1 and filling with the sign bit gives 0xFFFFFFFC, which is −4-4. The C division −7/2-7 / 2 rounds toward zero and gives −3-3. For an unsigned operand the two agree: 0xFFFFFFF0 >> 4 is 0x0FFFFFFF, that is, 4,294,967,280/16=268,435,4554{,}294{,}967{,}280 / 16 = 268{,}435{,}455.

Stated precisely

Let E1 have the promoted type TT of width NN bits, and let kk be the value of the promoted count E2. Let maxT\max T be the largest value of TT, and let ⌊x⌋\lfloor x \rfloor mean xx rounded down. C11, section 6.5.7, defines, for 0≤k<N0 \le k < N only: 𝙴𝟷 << 𝙴𝟸={E1⋅2kmod2Nif T is unsigned,E1⋅2kif T is signed, E1≥0 and E1⋅2k≤maxT,\texttt{E1 << E2} = \begin{cases} E1 \cdot 2^k \bmod 2^N & \text{if } T \text{ is unsigned}, \\ E1 \cdot 2^k & \text{if } T \text{ is signed, } E1 \ge 0 \text{ and } E1 \cdot 2^k \le \max T, \end{cases} 𝙴𝟷 >> 𝙴𝟸=⌊E1/2k⌋if T is unsigned or E1≥0.\texttt{E1 >> E2} = \lfloor E1 / 2^k \rfloor \quad \text{if } T \text{ is unsigned or } E1 \ge 0. Every case not listed is undefined behavior, except a right shift of a negative E1, which is implementation-defined behavior §4.13.

Checked against the rule with N=32N = 32: 1u << 31 gives 231mod232=2,147,483,6482^{31} \bmod 2^{32} = 2{,}147{,}483{,}648. 1 << 31 needs 231≤231−12^{31} \le 2^{31} - 1, which fails, so it is undefined. 1u << 32 has k=Nk = N, which fails k<Nk < N, so it is undefined although the left operand is unsigned.

Limits and common mistakes

Do not test a shift by performing it. Code that shifts first and then checks whether the result looks plausible has already executed the undefined operation, and the compiler may assume that the count was in range.

The width that matters is that of the promoted operand, not of the declared variable. Shifting a uint8_t left by 8 is allowed, because the shift runs in int; the high bits are lost only when the result is stored back into 8 bits.

A rotation is not a shift. C11 has no rotate operator, and the common idiom (x << n) | (x >> (32 - n)) for a 32-bit unsigned x is undefined for n=0n = 0, because it then shifts by 32. The form (x << (n & 31)) | (x >> (-n & 31)), with x of type uint32_t and n unsigned, is defined for every nn (the Bit operations entry covers rotation).

A shift of a signed value can be undefined even with a valid count: -1 << 1 is undefined in C11 because the left operand is negative. Use unsigned types for bit manipulation.

Other languages choose differently. Java uses only the low 5 bits of the count for an int and the low 6 bits for a long, so in Java 1 << 32 is 1. A rule from one language or processor cannot be assumed in another.

Questions answered

What happens for a negative shift count or one at least the operand width?

In C, a negative shift count and a count greater than or equal to the width of the shifted operand are both undefined behavior: the C standard (C11, section 6.5.7) places no requirement on the program, so no result can be relied on. The width is that of the left operand after integer promotion §4.18, not of the declared variable: a uint8_t is promoted to a 32-bit int on common machines, so counts 0 to 31 are allowed, x << 8 is fine, and x << 32 is undefined.

Processors do produce some result, but not the same one. x86, 64-bit Arm and RISC-V use the count modulo the width, so a 32-bit value shifted by 32 comes back unchanged, and a count of −1-1 acts as 31. 32-bit Arm uses the low 8 bits of the count, so a left shift by 32, or by −1-1, which reads as 255, moves every bit out and gives 0. An optimizing compiler may also assume that the count is in range. The eBPF instruction set, by contrast, defines the count explicitly as masked to 0–63 or 0–31. The safe practice is to check the count before shifting, for example n >= 32 ? 0 : x << n for a 32-bit unsigned x and an unsigned count n, when a shift by 32 or more should give 0.

Related entries: Integer promotion and conversion (§4.18), Implementation-defined behavior (§4.13), Undefined behavior (UB) (§4.12), Bit operations: truth tables, masks, shifts, and rotations (§4.50), Signed integer overflow (§4.15). Further reading: [6, 78, 160].