tags:

views:

331

answers:

3

I'm trying divide two numbers in assembly. I'm working out of the Irvine assembly for intel computers book and I can't make division work for the life of me.

Here's my code

.code
main PROC
    call division
    exit
main ENDP

division PROC
    mov eax, 4
    mov ebx, 2
    div ebx
    call WriteDec
    ret
divison ENDP

END main

Where WriteDec should write whatever number is in the eax register (should be set to the quotient after the division call). Instead everytime I run it visual studio crashes (the program does compile however).

+6  A: 

My memory is hazy on this, but IIRC you need to zero extend your EDX register before doing the division:

mov eax, 4
mov ebx, 2
sub edx, edx          ;set edx to zero
div ebx
call WriteDec

the ;set edx to zero is a comment in MASM, i don't know if it'll work if you are using inline assembly in C, so don't copy it if you are :)

slugster
Yes! Thank you very much for helping me with this.
Help I'm in college
Instead of zeroing EDX explicity, one would typically use the CDQ instruction to sign extend EAX into EDX. If EAX is non-negative, EDX is filled with zeros; if EAX is negative, EDX is filled with one-bits.
I. J. Kennedy
Yes, you are right in that respect, but the OP is doing *un*signed division, so i kept my answer simple.
slugster
A: 

i think the above mentioned reason is correct because when u divide eax by ebx both are 32 bit numbers but the dividend needs to be 64 bit divisor is 32 bit and so it considers edx as the msb...u may make edx 0 or instead of using 3bx use only bx..in that way u will divide a 32bit number by a 16 bit number

ruchir patwa
A: 

yes you need to set edx to zero fastest way of doing so is: xor edx, edx

Pianodervish