views:

385

answers:

1

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
...
+14  A: 

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.

Greg Hewgill
exactly. as Greg points out, a shift to the right by 1 is the same as a divide by 2 :-)
Fuzz
Thank you! 15 chars
DavidH