首页 > 解决方案 > 如何将负整数转换为字符串并在 MASM 程序集中输出

问题描述

我应该从用户那里获取有符号整数,计算输入数字的总和,然后显示平均值。问题是,负数似乎没有正确显示,尽管我知道总和和平均值计算正确。

为了正确显示负数,我需要在我的程序中添加什么内容?

.
.
.
writeVal PROC   USES eax
    LOCAL   resultString[11]:BYTE
    lea     eax, resultString
    push    eax
    push    [ebp + 8]
    call    intToStr
    lea     eax, resultString
    displayString eax ; print num
    ret     4

writeVal ENDP


intToStr PROC       USES eax ebx ecx
    LOCAL   tempChar:DWORD

    mov     eax, [ebp + 8]
    mov     ebx, 10
    mov     ecx, 0
    cld

divideByTen:
    cdq
    idiv    ebx
    push    edx
    inc     ecx
    cmp     eax, 0
    jne     divideByTen
    mov     edi, [ebp + 12] ; move into dest array
    jmp     storeChar

;store char in array

storeChar:
    pop     tempChar
    mov     al, BYTE PTR tempChar
    add     al, 48
    stosb
    loop    storeChar
    mov     al, 0
    stosb
    ret     8

intToStr ENDP
.
.
.

标签: assemblyx86masmsigned-integer

解决方案


You can simply check if the number is less than zero and then use neg instruction to negate it and apply the negative sign - to the resultString buffer:

Code for writeVal will be:

writeVal PROC USES eax ecx edi
    LOCAL   resultString[11]:BYTE
    lea     eax, resultString

    mov     ecx, [ebp + 8]          ; load passed number to ebx
    test    ecx, ecx                ; test number to see if it's less than zero
    jnl     non_negative            ; jump if not less to non_negative

    neg     ecx                     ; else we have a negative number so neg to make it positive
    mov     byte ptr [eax], '-'     ; set resultString[0] to '-'
    inc     eax                     ; increase resultString ptr + 1

    non_negative:

    push    eax                  ; push the resultString + 1
    push    ecx                  ; push the number
    call    intToStr             ; convert the number
    lea     eax, resultString
    printc  eax                  ; print num
    ret     4
writeVal ENDP

Compile and run:

start:

    push -14286754
    call writeVal

    exit

end start

Will print:

-14286754

推荐阅读