Search code examples
assemblysumdivisionmasm32

Print Number After using div and mod -not working MASM


I'm trying to write a program that get a String that contains number, and put in Sum2 variable the sum of the digits of the number that the function got. this is what I wrote but It doesn't work and I don't know why:

.386 
.MODEL Flat, STDCALL 
option casemap:none 

SomeFunc proto :DWORD

include \masm32\include\windows.inc
include \masm32\include\msvcrt.inc
includelib \masm32\lib\msvcrt.lib

.data

    Sum2 dd ?
    stop db 0
    fmt db '%s',0

.code

SomeFunc proc Number:DWORD
    Lop:
        mov eax,Number
        mov ebx,'10'
        xor edx,edx
        div ebx
        add Sum2,edx
        mov Number,eax
        cmp Number,0
        jna Lop
    ret
SomeFunc endp

start:
    invoke SomeFunc,'123'
    invoke crt_printf,offset Sum2,offset fmt
end start

I really don't understand why it doesn't work and how do I make it work. can someone explain me? Sorry for my bad english. thanks for the help.


Solution

  • Concentrating on SomeFunc

    • You should clear Sum2 before using this function. Without doing so you can only hope to be lucky 1 time.
    • You want to divide by 10 and not by a string '10'
    • You need to continue the loop for as long as EAX is not zero.

    Applying all of this gives:

    SomeFunc proc Number:DWORD
      mov Sum2, 0
      mov eax, Number
      mov ebx, 10
     Lop:
      xor edx, edx
      div ebx
      add Sum2, edx
      mov Number, eax
      cmp eax, 0
      jne Lop
      ret
    SomeFunc endp
    

    Do note that SomeFunc expects a number whereas invoke SomeFunc,'123' passes a pointer to a 3-character string.