TITLE Fast Multiplication (fastMultiplication.asm) Comment ! Description: Write a procedure named FastMultiply that multiplies any unsigned 32-bit integer by EAX, using only shifting and addition. Pass the integer to the procedure in the EBX register, and return the product in the EAX register. Write a short test program that calls the procedure and displays the product. (We will assume that the product is never larger than 32 bits.) Last update: 11/20/02 (uses new ReadDec procedure) ! INCLUDE Irvine32.inc INCLUDE Macros.inc .data str1 BYTE "Fast Multiplication Program - ** DEMO **", 0dh,0ah,0dh,0ah,0 .code main PROC call Clrscr mov edx,OFFSET str1 call WriteString L1: mWrite "Enter an unsigned integer (0 to quit): " call ReadDec .IF CARRY? mWrite <"Error: Integer is out of range",0dh,0ah> jmp L1 .ELSE mov ebx,eax .ENDIF cmp eax,0 je quit L2: mWrite "Enter an unsigned integer: " call ReadDec .IF CARRY? mWrite <"Error: Integer is out of range",0dh,0ah> jmp L2 .ENDIF mWrite <"--------------------------------",0dh,0ah> ; EBX = multiplicand, EAX = multiplier call FastMultiply ; EAX = product jc L1 ; CF=1 indicates error mWrite "The product is: " call WriteDec ; display product call Crlf call Crlf jmp L1 quit: exit main ENDP ;----------------------------------------------------------------- FastMultiply PROC uses ecx edx esi COMMENT ! Multiplies any unsigned 32-bit integer by EAX, using only shifting and addition. Receives: EBX = multiplier, EAX = multiplicand Returns: If CF=0, EAX = product; otherwise, CF=1 and EAX equals 0. The algorithm used here is more elegant than the one discussed on page 237. FOR count = 1 to 32 if lowbit(multiplier) == 1 product += multiplicand; ; check Carry flag multiplier SHR 1; multiplicand SHL 1; ; check Carry flag NEXT count This was obtained from the web site of Dr. Wang Jian-Sheng at the National University of Singapore (http://www.cz3.nus.edu.sg/~wangjs/) ----------------------------------------------------------------! mov edx,0 ; clear product to zero mov ecx,32 ; loop counter L1: test ebx,1 ; LSB set? jz L2 ; no: skip next statement add edx,eax ; yes: add multiplicand to product jc L3 ; display error if CF=1 L2: shr ebx,1 ; shift multiplier right shl eax,1 ; shift multiplicand left jc L3 ; display error if CF=1 loop L1 ; repeat for 32 bits L3: mov eax,edx ; return the product ret FastMultiply ENDP END main