Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP Posting-Version: version B 2.10.2 9/18/84; site uw-beaver Path: utzoo!watmath!clyde!burl!ulysses!mhuxr!mhuxt!houxm!vax135!cornell!uw-beaver!golde From: golde@uw-beaver (Helmut Golde) Newsgroups: net.lang.c Subject: Re: Right shift vs. divide Message-ID: <1733@uw-beaver> Date: Fri, 3-Jan-86 02:14:54 EST Article-I.D.: uw-beave.1733 Posted: Fri Jan 3 02:14:54 1986 Date-Received: Sat, 4-Jan-86 04:47:06 EST References: <974@brl-tgr.ARPA> <3000070@uokvax.UUCP> Reply-To: golde@uw-beaver.UUCP (Helmut golde) Organization: U of Washington Computer Science Lines: 31 Summary: 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