Reputation: 13
So, I am writing a program that divides two negative integers and stores the quotient and remainder, but it displays incorrect results. Here is my code:
mov eax, input1
mov edx, 0 ; dividend high half = 0. prefer xor edx,edx
mov ebx, input2 ; divisor can be any register or memory
div ebx
mov remainder, edx
mov edx, offset prompt
call Writestring
mov quotient, eax
call WriteDec
mov edx, offset prompt1
call Writestring
mov edx, remainder
call WriteDec
call Crlf
Upvotes: 1
Views: 193
Reputation: 58518
div
is used for unsigned division. For signed division you want idiv
. This takes a signed 64-bit dividend in edx:eax
, so you don't want edx
to be zero if the dividend is negative; rather, you want to sign extend eax
into edx
. This can be done with cdq
.
So I think you want
mov eax, input1
cdq
mov ebx, input2
idiv ebx
mov remainder, edx
mov quotient, eax
...
A couple other remarks:
Where does WriteDec
expect to find the number to be written? Check its documentation. You don't seem to be putting the results in any consistent register.
You are waiting until after calling Writestring
to save the quotient from eax
into memory. Are you sure Writestring
won't overwrite eax
? Many calling conventions would allow it to.
Your program will crash with a divide error if input2
is 0, or if input1
is 0x80000000
(the most negative 32-bit integer) and input2
is -1
. You may want to do some input checking if you don't already have it elsewhere.
As your comment says, idiv
can take its operand from register or memory. So there is no need to mov ebx, input2
when you can simply do idiv input2
. (Though you may also want to design your program so that input2
lives in a register all along and never needs to be stored in memory in the first place.)
Upvotes: 3