Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly fast division by 2

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
...
like image 571
DavidH Avatar asked Jan 10 '10 10:01

DavidH


People also ask

What is SHR in assembly?

The SHR (shift right) instruction performs a logical right shift on the destination operand. The highest bit position is filled with a zero.

How is division done in assembly?

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.


1 Answers

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:

  • for x = 0, the result is 0
  • for x > 0, the result is floor(x / 2)
  • for x < 0, the result is also floor(x / 2), or -ceil(-x / 2)

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.

like image 65
Greg Hewgill Avatar answered Oct 17 '22 07:10

Greg Hewgill