The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
0 votes
259 views
asked in Digital Logic by (13 points) | 259 views

1 Answer

+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.

Reference: http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-manual-325462.pdf
 

answered by Veteran (349k points)
selected by


Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

36,203 questions
43,662 answers
124,117 comments
42,947 users