Search code examples
assemblyx86division

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

  • 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.