MASM: integer to string using std and stosb

2019-08-09 05:00发布

I have the following procedure for converting a user supplied integer to a string. I'm pretty sure my algorithm is working fine for converting each digit of the integer to it's correct decimal ASCII value. However, I'm having difficulty then storing that digit into its correct place in the outString.

I've set the direction flag using 'std', and I then use stosb to load the current, converted digit into the last byte in outString (read from back to front). However, this does not seem to work.

If I get rid of 'std', I can store my converted integer in reverse. E.g 1993 gets stored in outString as '3991', but obviously that's in error.

Would appreciate some assistance. Am I using 'std' wrong? Thanks!

writeVal PROC

; SET up the stack frame 
push    ebp     ;old value of ebp stored on the system stack
mov ebp, esp    ;ebp now contains value of esp, which is address of top of stack


mov edi, [ebp + 8]      ; EDI = @outString



std                 ; set direction flag. allows us to add chars to the end of outString


mov eax, [ebp + 12] ; EAX = userInt

convertInt:             ; the int->string conversion is a post-test loop to handle case where user input '0' as a string

    mov ebx, 10d            ; EBX = divisor of 10
    cdq                 ; prep for division
    div ebx             ; EAX = quot, EDX = remainder

    add edx, 48         ; convert EDX to ASCII char value

    push    eax             ; store current value in EAX
    mov eax, edx            ; set EAX to the converted ASCII value


    stosb               ; store the converted char at the end of outString

    pop eax             ;restore value of EAX

    call WriteDec
    call CrLf

    cmp eax, 0
    je  finished            ; if eax = 0, it means we have fully converted userInt to a string
    jmp convertInt      ; else, repeat

finished:
    displayString [ebp + 8] ; print the converted outString

    pop ebp
    ret 8
writeVal ENDP 

1条回答
家丑人穷心不美
2楼-- · 2019-08-09 05:07

Since you have a variable for the number of digits, this is how you specify the end of the string.

mov edi, [ebp + 8]      ; EDI = @outString
add edi, NumberOfDigits
dec edi                 ;When DF=1 STOSB starts here
查看更多
登录 后发表回答