x86基础实验-阶乘(堆栈传参实现)

简介

输入一个16进制数,使用堆栈传参的方式实现阶乘的计算并以16进制输出结果

程序运行结果
3的阶乘

5的阶乘

6的阶乘

7的阶乘
n=3时栈的情况
debug截图

分析
代码
ASSUME  CS:CODE1,DS:DATA1,SS:STACK1

STACK1  SEGMENT STACK
STACK_AREA      DW      200H DUP(?)
STACK_BTM       EQU     $-STACK_AREA
STACK1          ENDS

DATA1   SEGMENT
RESULT      DW  1

DATA1   ENDS


CODE1 SEGMENT


FACT    PROC    NEAR ; [SP+2] return address [SP+4] n
    PUSH    BP
    MOV     BP,SP
    PUSH    CX
    PUSH    AX
    PUSH    BX


    MOV     BX,[BP+4]
    MOV     AX,[BP+6]
    CMP     AX,1
    JE      FACT_EXIT 

    SUB     AX,1
    PUSH    AX
    PUSH    BX
    CALL    FACT
    MOV     AX,[BX]

    MOV     CX,[BP+6]
    MUL     CX

    MOV     [BX],AX

FACT_EXIT:

    POP     BX
    POP     AX
    POP     CX
    POP     BP
    RET     4

FACT    ENDP


MAIN PROC FAR

        MOV     AX,STACK1
        MOV     SS,AX
        MOV     SP,STACK_BTM
        MOV     AX,DATA1
        MOV     DS,AX
        MOV     ES,AX
    
        MOV     BX,0
    READHEX_LOOP:
        MOV     AH,01
        INT     21H
        CMP     AL,'0' 
        JB      READHEX_LOOP_END
        CMP     AL,'9'
        JA      READHEX_ASCII
        SUB     AL,'0'
        JMP     READHEX_READ  

    READHEX_ASCII:
        OR      AL,32
        CMP     AL,'a'
        JB      READHEX_LOOP_END
        CMP     AL,'f'
        JA      READHEX_LOOP_END
        SUB     AL,'a'-10

    READHEX_READ:
        SHL     BX,1
        SHL     BX,1
        SHL     BX,1
        SHL     BX,1

        MOV     AH,0
        ADD     BX,AX
        
        JMP     READHEX_LOOP

    READHEX_LOOP_END:
    
        PUSH    BX
        MOV     BX,OFFSET RESULT
        PUSH    BX
        CALL    FACT

        MOV     CX,4
        MOV     AX,RESULT

    OUTPUT16_LOOP:
        ROL     AX,1
        ROL     AX,1
        ROL     AX,1
        ROL     AX,1

        MOV     DL,AL
        AND     DL,15
        
        CMP     DL,10        
        JAE     OUTPUT_ASCII

        ADD     DL,'0'
        JMP     OUTPUT_NEXT

    OUTPUT_ASCII:
        ADD     DL,'A'-10

    OUTPUT_NEXT:    
        PUSH    AX
        MOV     AH,02H
        INT     21H
        POP     AX

        LOOP OUTPUT16_LOOP

        MOV     AX,4C00H
        INT     21H

MAIN    ENDP
CODE1   ENDS

END     MAIN



你可能感兴趣的:(x86基础实验-阶乘(堆栈传参实现))