Problem converting integer to ASCII code in x86 assembly

点点圈 提交于 2019-12-20 06:31:04

问题


I am trying to use the code below to convert an integer in ax to ASCII codes. But running it outputs 515, rather than 513 as I expected. Where is the error?

stk segment
    dw 32 dup(0)
stk ends
dts Segment
    posnum db 6 dup(0) ;0<x<65536;
dts ends
cds Segment
    Assume cs:cds , ds:dts,ss:stk
    Main Proc Far

     mov ax,seg dts
     mov ds,ax
     mov es,ax
     xor ax,ax

     mov ax,513

     mov di,offset posnum

     Call ConvertPositive

     mov ah,09h
     mov dx ,offset posnum
     int 21h
    main_finish:
        mov ah,08h
        int 21h
        mov ax,4c00h
        int 21h
    Main endp
cds Ends

procs segment
    assume cs:procs
    ConvertPositive proc far
        xor dx,dx
        xor cx,cx
        mov bl,10
        mov bh,0
        divloop:
            mov dx,0
            div bx
            add dl,30h
            mov byte ptr [si],dl
            inc cl
            inc si
            cmp ax,0
            jne divloop
        enddiv:
            dec si
            copy:
                std
                LODSB
                cld
                STOSB   
            loop copy
            mov byte ptr [di],'$'
        ret
    ConvertPositive endp
procs ends
end Main

回答1:


SI is not initialized. It should point to a buffer allocated for the reverse order digits.




回答2:


Your divide loop looks good

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

 int main ( void )
 {
     unsigned int ax;
     unsigned int dx;

     ax=513;

     while(ax)
     {
        dx=ax%10;
        ax=ax/10;
        printf("%c",dx+0x30);
     }
     printf("\n");
 }

I get 315 out of the above loop.

I suspect when you try to flip the string around your 5 is stomping on your 3. Try a number like 713 and see if it results in 717. 523 if you get 525, etc. I am guessing 1234 results in 4334.



来源:https://stackoverflow.com/questions/4639745/problem-converting-integer-to-ascii-code-in-x86-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!