使用visual studio中的atod宏来解决汇编语言问题

时间:2017-10-05 02:51:29

标签: assembly macros

如果我没有弄错的话,宏似乎正在工作,因为任何两个数字中的一个与另一个数字交换。但是,交换的第二个数字会导致垃圾输出。例如,用户输入4然后输入5.交换应该输出第一个数字5然后输出4.在这种情况下,4只是垃圾数字。

.586
.MODEL FLAT

INCLUDE io.h            ; header file for input/output

.STACK 4096

.DATA 

number1 DWORD ?
number2 DWORD ?

prompt1 BYTE "Enter the first number", 0
prompt2 BYTE "Enter the second number", 0

stringIn BYTE 20 DUP (?)

outputNum1Lbl BYTE "The first number you entered", 0
input1 BYTE 11 DUP (?), 0
outputNum2Lbl BYTE "The second number you entered", 0
input2 BYTE 11 DUP (?), 0
swapNum1Lbl BYTE "The new first number is", 0
newNum1 BYTE 11 DUP (?),0
swapNum2Lbl BYTE "The new second number is", 0
newNum2 BYTE 11 DUP (?), 0

.CODE
_MainProc PROC
    input prompt1, stringIn, 20
    atod stringIn
    mov eax, number1

    input prompt2, stringIn, 20
    atod stringIn
    mov number2, ebx

    xchg eax, ebx
    dtoa newNum1, ebx
    dtoa newNum2, eax

    output swapNum1Lbl, newNum1
    output swapNum2Lbl, newNum2

    mov eax, 0
    mov ebx, 0
    ret
_MainProc ENDP

END                             ; end of source code

1 个答案:

答案 0 :(得分:2)

此代码中无需使用内存变量。只需将第一个输入存储在EBX寄存器中,并将第二个输入保留在EAX寄存器中。

input prompt1, stringIn, 20
atod stringIn
mov ebx, eax

input prompt2, stringIn, 20
atod stringIn

xchg eax, ebx
push eax
dtoa newNum1, ebx
pop  eax
dtoa newNum2, eax

因为“dtoa”可能会破坏EAX,您可以选择暂时将其保存在堆栈中。

  

“新的第一个数字是”

     

“新的第二个数字是”

这些标签有点误导!

“dtoa”和“atod”的定义

dtoa        MACRO  dest,source         ; convert double to ASCII string
            push   ebx                 ; save EBX
            lea    ebx, dest           ; destination address
            push   ebx                 ; destination parameter
            mov    ebx, [esp+4]        ; in case source was EBX
            mov    ebx, source         ; source value
            push   ebx                 ; source parameter
            call   dtoaproc            ; call dtoaproc(source,dest)
            add    esp, 8              ; remove parameters
            pop    ebx                 ; restore EBX
            ENDM

atod        MACRO  source              ; convert ASCII string to integer in EAX
            lea    eax,source          ; source address to AX
            push   eax                 ; source parameter on stack
            call   atodproc            ; call atodproc(source)
            add    esp, 4              ; remove parameter
            ENDM