Is left shifting an unsigned int or unsigned char by 1 always equivalent to multiplying by 2 (in practical C/C++ code)?

Difficulty: Medium

Correct Answer: Incorrect — it fails when the result would overflow the type width

Explanation:


Introduction / Context:
Programmers often say “left shift by 1 multiplies by 2.” While this is commonly true, the always in the statement can be misleading. Understanding when the equivalence holds and when it breaks is crucial for writing correct, portable bit-level code in C/C++.


Given Data / Assumptions:

  • We are dealing with unsigned integers (e.g., unsigned int or unsigned char).
  • Left shift operator «<<» and multiplication by 2 are compared.
  • The machine uses fixed-width unsigned types (e.g., 8, 16, 32 bits).


Concept / Approach:
For unsigned types, left shift by k mathematically corresponds to multiplication by 2^k modulo 2^N, where N is the bit width. If the mathematical product stays within the representable range (no high bits lost), the operations agree. However, when the product requires more than N bits, left shift discards the overflowing bits, effectively wrapping modulo 2^N. Saying “always equivalent” ignores this overflow/wrap aspect. In contrast, the phrase “multiply by 2” usually implies mathematical integer multiplication without wraparound.


Step-by-Step Solution:

Let N = 8, x = 200. x << 1 = 144 (since 200 * 2 = 400, and 400 mod 256 = 144).Mathematically, 200 * 2 = 400; this cannot be represented in 8 bits. The left shift wrapped, so it is not equivalent to the mathematical product.If x = 60, x << 1 = 120, which matches 60 * 2, since no overflow occurs.


Verification / Alternative check:
Use wider types (e.g., unsigned long long) to see when overflow occurs. If you need guaranteed mathematical multiplication, promote to a wider type before shifting or multiplying.


Why Other Options Are Wrong:

“Correct — for all values”: ignores wrap.Endianness is irrelevant to arithmetic equivalence.“Only if the value is odd”: parity does not govern overflow here.“Equivalent only for signed integers”: signed left-shift has additional rules and potential undefined behavior on overflow.


Common Pitfalls:
Assuming left shift is a safe substitute for multiplication in all cases; overlooking overflow and silent wrap behavior.


Final Answer:
Incorrect — it fails when the result would overflow the type width.

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion