开发者

Assembly fast division by 2

Is there a faster way of dividing by 2, with sign, in assembly than the one in the exam开发者_JS百科ple 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:

  • 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜