Computer Arithmetic
Which expression multiplies an integer x by 10 using shifts and additions instead of a multiply instruction?
- A(x << 3) + (x << 1)
- B(x << 10)
- C(x << 2) + x
Show answer and explanation
Answer: A. (x << 3) + (x << 1)
Shifting left by one bit doubles a value, so x << 3 is 8x and x << 1 is 2x. Since 8x + 2x = 10x, (x << 3) + (x << 1) computes ten times x. Multiplication by a constant can be replaced this way with shifts and additions, and compilers choose whichever is faster. x << 10 multiplies by 2¹⁰ = 1024, and (x << 2) + x gives 4x + x = 5x. Be careful not to confuse the shift amount with the multiplier.
- A. Correct. 8x + 2x = 10x.
- B. x << 10 multiplies by 1024.
- C. (x << 2) + x multiplies by 5.