首页 > 解决方案 > 汇编打印 n 位数字

问题描述

我为我可能用英语犯的每一个错误道歉(这不是我的母语)。

我试图打印一个大于 9 的数字。我将它划分为每个数字,然后我一个接一个地打印它们。该代码有效,但它也会打印其他字符,然后再给出错误并停止工作。

这里的代码:

.386 
.model flat,stdcall 
option casemap:none 
include \masm32\include\windows.inc 
include \masm32\include\user32.inc 
includelib \masm32\lib\user32.lib
include \masm32\include\kernel32.inc 
includelib \masm32\lib\kernel32.lib
include \masm32\include\masm32.inc
includelib \masm32\lib\masm32.lib
.data
    textNum dd "c",0                                            ;variable i use to display every single digit (initialized with a casual character)
    num dd 25678                                                ;number to print
    divisor dd 10
.code
    start:
        mov eax, num
        xor ecx,ecx                                             ;ecx is the digits counter
        lea esi, textNum                                        ;mov in esi the adress of textNum
        ciclo:
            cmp eax,0                                           ;when the dividend is 0 exit
            jbe print

            xor edx,edx                                         ;reset edx to take the remainder
            div divisor
            push edx                                            ;push the remainder

            add cl,1                                            ;increase digits counter
            jmp ciclo

        print:
            cmp cl,0                                            ;since the counter is greater than 0
            jbe return

            xor eax,eax
            pop eax                                             ;pop in eax the digit i want to print
            add eax,48                                          ;add 48 (ascii value)
            mov [esi], eax                                      ;move the digit inside the variable

            invoke StdOut, addr textNum                         ;print the variable

            sub cl, 1                                           ;dec counter
            jmp print
        return:
            invoke ExitProcess, 0
    end start

这里是截图

这个数字是正确的,但在那之后还有更多的东西......为什么会发生这种情况,我该如何避免它?

编辑:我也尝试在不更改其余代码的情况下使用数组。第一个元素是 i 更改的元素,第二个元素是终止符(始终为 0):

;textNum dd "c",0                                            ;variable i use to display every single digit (initialized with a casual character)
textNum dd 2 dup(0)

但它仍然存在问题

标签: winapiassemblyprinting

解决方案


我试图用 edi 更改用作计数器(ecx)的寄存器,现在它可以工作了。也许 StdOut 使用 ecx 并改变了他的价值


推荐阅读