Writing int to unsigned char* in Assembly

I am trying to write a function similar (although a bit simpler) than sprintf. I have come to the point where I am supposed to print integers to the result string -- argument %d. My strategy is to divide the number by 10 and add 48 (ascii offset) to the rest, then push it on the stack and increase esi, until the quotient is 0. Then I pop each number off the stack, and add them to the result string. This is my current code:

addint:

    movl        $0,%edx
    movl        $10,%ebx
    div         %edi

    addl        $48,%edx

    pushl       %edx
    incl        %esi

    cmpl        $0,%eax
    jz          addintprint
    jmp         addint


addintprint:

    movl        tmpedx,%edx
    incl        %ecx
    jmp         addintfinish


addintfinish:

    cmpl        $0,%esi
    jz          mainloop

    decl        %esi

    popl        %ebx

    movl        addr,%eax
    leal        (%edx,%eax,1),%eax
    movb        %bl,(%eax)

    incl        %edx

    jmp         addintfinish

Where %edx is used to count the letter index in the result string (%ecx has been reserved for the purpose of counting up indexes in the second parameter string, so please don't use it unless it's necessary), and addr is the address of the result string.

Right now I get silly outputs (ranging from twice the argument to letters such as L and other randomness from the ascii table). I think I'm on the right track, but something's obviously wrong with my current code. Any help is greatly appreciated.

Thanks in advance.

Upvotes: 0

Views: 819

Answers (1)

Jester
Jester

Reputation: 58822

You load 10 into ebx but use edi in the division. There might be other issues too. Learn to use a debugger to step through your code and see where it goes wrong yourself.

Upvotes: 1

Related Questions