0

I'm trying to print a number stored in EBX to a pointer in EDI and for some reason the second time the loop goes and divides eax by 10 the problem happens. So when I ran the code the first loop turns 8000 into CCC and the second turns CCC into CCCCCE14. I don't understand why this is happening.

The value of ebx is FFFF8000=-32768 when the procedure is called and edi points to value + 3.

value db 10,13,'         $'
ten dd 10 
mone dd -1
minus db '-$'
printnum proc near ;print ebx starting from position edi in string value
    mov ecx,0
    mov eax,ebx
    cmp eax,0    ;check if number is negative
    jg goagain
    mov ah,9
    mov dx,offset minus 
    int 21h
    mov eax,ebx
    imul mone       ;print a minus and convert number to positive

goagain:    
    inc ecx      ;counter
    div ten
    push edx
    cmp eax,0
    jne goagain
    dec ecx
poprint:
    pop ebx
    add ebx,'0'
    mov [edi+ecx],edx
    dec ecx
    cmp ecx,0
    jge poprint
    ret
printnum endp
Ross Ridge
  • 38,414
  • 7
  • 81
  • 112
Dani
  • 79
  • 2
  • 12
  • 5
    You don't set `edx` to anything reasonable before the division. Btw: there's a `neg` instruction, you don't have to multiply by -1. – harold Apr 17 '16 at 19:16
  • 1
    HAHA!!!! it WORKS!!! i added MOV EDX,0 befor the div and the code does not fully work but at least it does not get stuck in an endless loop!!! thank you!!! – Dani Apr 17 '16 at 19:21
  • You should have read some documentation, like the x86 wikibook. div divides edx:eax by the argument and returns the remainder in edx and the quotient in eax, in other words: if your division has a remainder your next division will use it as the higher 32bits of your dividend. – S.Klumpers Apr 17 '16 at 19:26
  • Just another observation. Your code is a mixture of 16-bit DOS interrupts and 32-bit code (you use 32-bit registers etc). For example: `mov [edi+ecx],edx` is 32-bit addressing. This may work in your environment but wouldn't work on an 8086/8088/80286 processors. This may not be an issue at all for you, but I felt it should be mentioned. – Michael Petch Apr 17 '16 at 19:29
  • hi S.Klumpers I did read the documentation but didnt really undertand what EDX has to do with EAX when i use div what i did understand is the remainder goes in edx. but if edx has a value in it and i use div I have no clue how the calculation would work. still after you explained im still not sure. an example would be very helpful. and Michael this code is .386 i know it would not work in 8086. thanks for mentioning. – Dani Apr 17 '16 at 19:37
  • Then you were reading poor documentation. See the [x86 tag wiki](http://stackoverflow.com/tags/x86/info) for links to Intel's insn ref manual. – Peter Cordes Apr 18 '16 at 00:58
  • Possible duplicate of [Why "DIV EDX" in MASM always generates processor exception?](http://stackoverflow.com/questions/12231784/why-div-edx-in-masm-always-generates-processor-exception) – Peter Cordes Apr 18 '16 at 00:59

0 Answers0