The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
0 votes
asked in Digital Logic by (13 points) | 273 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.


answered by Veteran (369k points)
selected by

Related questions

+2 votes
0 answers

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

44,284 questions
49,773 answers
65,856 users