The Gateway to Computer Science Excellence

+4 votes

Best answer

I guess you meant multiplication and division by power of 2. For multiplication your question answers itself, as answer is always an integer. For division, answer to your question is "yes"- it won't work. Because when we use shift instead of division, compiler will just use shift instruction provided by the CPU (if it does). So, lets take Intel architecture and this is what Intel manual says for SAR (Shift Arithmetic Right) Instruction.

"Using the SAR instruction to perform a division operation does not produce the same result as the IDIV instruction.

The quotient from the IDIV instruction is rounded toward zero, whereas the “quotient” of the SAR instruction is

rounded toward negative infinity. This difference is apparent only for negative numbers. For example, when the

IDIV instruction is used to divide -9 by 4, the result is -2 with a remainder of -1. If the SAR instruction is used to

shift -9 right by two bits, the result is -3 and the “remainder” is +3; however, the SAR instruction stores only the

most significant bit of the remainder (in the CF flag)"

So, for positive numbers, when we want only the quotient we can safely use shift in place of division by power of 2. Otherwise we should not use shift.

52,345 questions

60,471 answers

201,800 comments

95,278 users