Quickly split assembly into 2

Is there a faster way to divide by 2 with a sign in the assembly than the one shown in the example below?

... mov ecx, 2 idiv ecx push eax #push the result ... 
+7
assembly division
source share
1 answer

Of course:

 sar eax, 1 

The sar differs from shr in that the most significant (signed) bit is stored in sar , and it is set to 0 in shr . The Wikipedia page of the Arithmetic Shift shows much more detailed information about this operation in a general context.

Note that on a machine with two additions (which is x86) this actually computes floor(eax / 2) . In particular, this 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 gender (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 leads to 1.

+21
source share

All Articles