'Divide overflow in Assembly language
I have a simple assembly program, where I want to divide two numbers (two byte sized) and print remainder. Here's my code
.model small
.stack 256
.data
ten dw 10
.code
main proc
mov ax, @data
mov ds, ax
mov ax, 12 ; divident
div ten ; ax/10
mov ah, 9 ; for printing dx
int 21h
mov ax, 4c00h ; ending program
int 21h
main endp
end main
So when I run this code the result is "Divide overflow" and I have no idea why does overflow happens. Any ideas?
Solution 1:[1]
DIV mem16 divides DX:AX by the given operand. So you need to zero-extend AX into DX, with MOV DX,0 or XOR DX,DXI.e.:
mov ax,12
xor dx,dx
div ten
(Before signed division with idiv, use cwd to sign-extend AX.)
Another problem with your code is that you seem to assume that int 21h / ah=9 can be used to print numeric values. That is not the case. If you want to print the value of DX (i.e. the remainder) you'll have to convert it into a string first and print that string. Otherwise you'll just get garbage output, and your program might even crash.
Solution 2:[2]
Write "ten DB 10" or "div BYTE PTR ten".
And I am sure if you write something like
mov cl, 10
div cl
you'll also get what you want. If it should be word division, you must to clear DX, Michael wrote in post below, how.
BTW I don't know, what assembly dialect it is, but do you really need to write this?
mov ax, @data
mov ds, ax
Doesn't DS point to data section by defaut?
And 09h doesn't do what you want. Take a look at 02h.
Solution 3:[3]
.model small
.stack 256
.data
ten dw 10
.code
main proc
mov ax, @data
mov ds, ax
mov ax, 12 ; divident
div ten ; ax/10
add dl,48;
mov ah, 02h ; for printing dl not the ascii vlaue
int 21h
mov ax, 4c00h ; ending program
int 21h
main endp
end main
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Cordes |
| Solution 2 | |
| Solution 3 | ChrisMM |
