0

I am trying to divide a negative number. I read that I need to use idiv, but it still outputs 5 instead of -5

.386
.model flat,stdcall
option casemap:none

include \masm32\include\masm32rt.inc

.data
AnswerTxt   db   'The answer is '
AnswerNum   db   11 dup(0)
num_a dd 5

.code
start:
     xor edx, edx
     mov eax, -25
     mov ebx, num_a
     idiv ebx

     push offset AnswerNum
     push ebx
     call dwtoa
     push 0
     push offset AnswerTxt
     push offset AnswerTxt
     push 0
     call MessageBoxA
     call ExitProcess
end start

UPDATE (problem solved):

.386
.model flat,stdcall
option casemap:none

include \masm32\include\masm32rt.inc

.data
AnswerTxt db 'The answer is '
AnswerNum db 11 dup(0)
num_a dd 5

.code
start:
     mov eax, -25
     mov ebx, num_a
     cdq
     idiv ebx

     push offset AnswerNum
     push eax
     call dwtoa
     push 0
     push offset AnswerTxt
     push offset AnswerTxt
     push 0
     call MessageBoxA
     call ExitProcess
end start
John
  • 345
  • 2
  • 14
  • 2
    `xor edx, edx` zero extends. You need to sign extend. Use `cdq` **after** `mov eax, -25`. Also you are printing `ebx` which is of course still `5`. You want to print `eax`. Finally, your `dwtoa` that you did not show might not even be able to print signed numbers. – Jester Mar 23 '20 at 15:00
  • @Jester thank you for your answer! "dwtoa" is from masm32rt.inc I added cdq and changed print to eax, but it outputs "858993454". Is there an alternative to this "dwtoa" for me to output a decimal in MessageBox? – John Mar 23 '20 at 15:24
  • Are you sure you put the `cdq` in the correct place? You'd get `858993454` if you did it wrong. [Update your post with the current code](https://stackoverflow.com/posts/60815993/edit) – Jester Mar 23 '20 at 15:57
  • @Jester oh, after your suggestions I also put `xor edx, edx` after the two `mov` and somehow this changes the behavior. Now with `xor edx, edx` in the beginning it outputs -5 ok! Thank you very much! But why is that? Almost every code I've seen use it after `mov`s and before the `div`. Moving it in the beginning was purely my decision, cause "why not". – John Mar 23 '20 at 16:39
  • As I said in my first comment, `xor edx, edx` zero extends. Use that only for unsigned numbers. – Jester Mar 23 '20 at 16:41
  • 1
    oh, I did not understand that I need to use `cdq` instead of `xor edx, edx` :) Thank you once more! – John Mar 23 '20 at 16:50

0 Answers0