Bitwise shifts include left-shift operations of the form shift-expression <<
additive-expression and right-shift operations of the form shift-expression >>
additive-expression. The integer promotions are performed on the operands, each of which has an integer type. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
...
The following code can result in undefined behavior because there is no check to ensure that left and right operands have nonnegative non-negative values and that the right operand is less than or equal to the width of the promoted left operand.
...
The result of E1 << E2
is E1
left-shifted E2
bit positions; vacated bits are filled with zeros. According to C99, if E1
has an unsigned type, the value of the result is E1 * 2 E2
, reduced modulo one more than the maximum value representable in the result type. Although C99 specifies modulo behavior for unsigned integers, unsigned integer overflow frequently results in unexpected values and resultant security vulnerabilities (see INT32-C. Ensure that operations on signed integers do not result in overflow). Consequently, unsigned overflow is generally non-compliant , and E1 * 2 E2
must be representable in the result type. Modulo behavior is allowed if the conditions in the exception section are met.
...
This compliant solution eliminates the possibility of undefined behavior resulting from a left-shift operation on unsigned integers. Example solutions are provided for the fully compliant case (unsigned overflow is prohibited) and the exceptional case (modulo behavior is allowed).
...