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
...
The SHR (shift right) instruction performs a logical right shift on the destination operand. The highest bit position is filled with a zero.
div executes unsigned division. div divides a 16-, 32-, or 64-bit register value (dividend) by a register or memory byte, word, or long (divisor). The quotient is stored in the AL, AX, or EAX register respectively. The remainder is stored in AH, Dx, or EDX.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With