The inputs to the function should be the 16-bit signed base in the Ax register and the 8-bit unsigned exponent in the Dl register. The 32-bit signed function result is returned in the eAx register. Additionally, the BL register serves as an overflow indicator, returning a 0 to indicate that no overflow occurred and a 1 on overflow. The exponentiation function must save and restore all registers and flags except eAx and BL.
BL=1
.386
.model flat, stdcall
include v:\common\user\c335\masm32\include\kernel32.inc
include v:\common\user\c335\masm32\include\masm32.inc
includelib v:\common\user\c335\masm32\lib\kernel32.lib
includelib v:\common\user\c335\masm32\lib\masm32.lib
PutDec proto
GetDec proto
PutStrng proto
.data
Error db 'Error...Cannot compute N!'
Prompt db 'Enter unsigned number:'
.code
Main Proc Near
Mov eCx, 22 ; cout << "Enter unsigned number:";
Lea eDi, Prompt
Call PutStrng ; cin >> eAx;
Call GetDec
Call Factorial ; eAx = Factorial(Ax)
Ifa: ; if (Ch == 0)
Cmp Ch, 0 ; cout << eAx;
Je Thena ; else cout << Error;
Jmp Elsea
Thena:
Call PutDec
Jmp EndIfa
Elsea:
Lea eDi, Error
Mov eCx, 25
Call PutStrng
Endifa:
Push 0 ; Stop
Call ExitProcess
Main Endp
|
;; int Factorial (int Ax);
;; - Calculate N!
;; Parameters - Ax positive integer value
;; Returns - eAx factorial value on return
;; Registers Altered - Ch, eAx
Factorial Proc Near ;; int Factorial(int Al)
;; { ______________
Push eDx ;; |Save registers|
Push eBx ;; |______________|
PushfD
Mov eDx, 0 ;; Convert Ax to unsigned 32-bit
Mov Dx, Ax
Mov eAx, eDx
Mov eBx, eAx
Mov eAx, 1 ;; F := 1
Mov Ch, 0 ;; Ch = 0
Fora: Cmp eBx, 1 ;; for(eBx=eAx,Ch=0; eBx>1 && Ch==0; eBx--)
Ja Anda ;; F := F * N
Jmp EndFora ;; If Overflow
Anda: Cmp Ch, 0 ;; Ch = 1;
Je Doa ;; eBx = eBx - 1;
Jmp EndFora
Doa:
Mul eBx
Ifc:
Jo Thenc
Jmp EndIfc
Thenc:
Mov Ch, 1
EndIfc:
Dec eBx
Jmp Fora
EndFora:
PopfD
Pop eBx ;; _________________
Pop eDx ;;|Restore registers|
Ret ;;|_________________|
Factorial Endp
End Main
|