Right shift vs. divide

Helmut Golde golde at uw-beaver
Fri Jan 3 17:14:54 AEST 1986


Microsoft C for 8086/8088 seems to successfully optimizes integer divides
into right shift, when optimizing for reduced execution speed.  Here's is
the actual code produced (with comment for those unfamiliar with the 8086).

Y = X / 2     ------>

mov ax,X	;mov variable X into register ax
cwd		;convert AX to double word, high part in DX
sub ax, dx	;ax -= dx
sar ax,1	;shift arithmetic right ax 1 bit
mov Y,ax	;move ax to variable Y

So far so good.  It seems to work.  But get how it compiles larger divisions!

Y = X / 8  (or any other power of 2)     ------------>

mov ax, X	;register ax = variable X
cwd		;word to double word, high part in dx
xor ax,dx	;ax = ax xor dx
sub ax,dx	;ax -= dx
mov cx,3	;cx = 3 (or whatever the shift count should be)
sar ax,cx	;shift ax arithmetic right cx bits
xor ax,dx	;ax = ax xor dx
sub ax,dx	;ax -= dx
mov Y,ax	;variable Y = ax

It even seems to work, and I guess it is faster than an integer divide.
Amazing, though.


--Peter Golde



More information about the Comp.lang.c mailing list