程序集打印n位数字

时间:2018-04-24 17:59:11

标签: winapi assembly printing

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

我试图打印一个大于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

Here a screenshot

这个数字是正确的,但之后会有更多的东西...为什么会发生这种情况,我怎么能避免呢?

编辑: 我还试图在不改变其余代码的情况下使用数组。第一个元素是我改变的元素,第二个元素是终止符(总是0):

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

但它仍然存在问题

1 个答案:

答案 0 :(得分:0)

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