Hello all,

can anyone explain the difference between SAR and IDIV. From my quick reference booklet I see that both do signed divisions by 2 ... what confuses me is the rounding operation. For SAR my booklet says that it does this
division with "rounding toward negative infinity" while for the IDIV instruction it says that non integral quotients are truncated toward 0.

Thank you.


yaa
Posted on 2003-09-02 14:35:06 by yaa
For example set ax = -5

If you want to do ax / 2 you get two different quotients



mov ax , -5
mov bl, 2
idiv

al = -2
otherwise


mov ax , -5
sar ax, 1

al = -3
Posted on 2003-09-02 14:49:08 by greenant
Description from Intel, I think the best:

"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)."
Posted on 2003-09-02 15:24:21 by MazeGen
MazeGen you have been very clear. greenant thank you too ... even if you have succeded in confusing me at first with you code examples ...

yaa
Posted on 2003-09-02 15:48:58 by yaa


sar <reg>, <value>
jns @F
sbb <reg>, 0
@@:


This should end up with the same result as idiv, I think...

Mirno
Posted on 2003-09-02 17:41:04 by Mirno
mov eax,-11
sar eax,2
jns @F
sbb eax,0
@@:
; EAX = -3
Posted on 2003-09-02 23:26:11 by bitRAKE
This act like IDIV only if you divide by 2


mov eax, <value>
sar eax, 1
jns @F
adc ax, 0
@@:

In this way ax == quotient
Posted on 2003-09-03 01:46:56 by greenant