Is there a faster way of dividing by 2, with sign, in assembly than the one in the example below?
...
mov ecx, 2
idiv ecx
push eax #push the result
...
Is there a faster way of dividing by 2, with sign, in assembly than the one in the example below?
...
mov ecx, 2
idiv ecx
push eax #push the result
...
Sure:
sar eax, 1
The sar
opcode differs from shr
in that the most significant (sign) bit is preserved in sar
, and it is set to 0 in shr
. The Arithmetic shift page on Wikipedia shows much more detail about this operation in a general context.
Note that on a 2's complement machine (which the x86 is) this actually calculates floor(eax / 2)
. In particular, that means that for an integer x:
The latter result gives results that may be unexpected. For example, -3 sar 1 results in -2, not -1. On the other hand, 3 sar 1 results in 1.