0

The following program works perfectly fine, but I need to understand one step that I don't understand so far.

Look at the code first: I'll indicate the problem as comment right beside where my question is about.

.data  
  mesg byte "How many miles did you fill:", 0dh, 0ah, 0
  mesg1 byte "How many gallons did you drive:", 0dh, 0ah, 0
  mesg2 byte "Your car goes miles per gallon:", 0dh, 0ah, 0
  miles DWORD ?
  gallons DWORD ?

.code
  main proc

    mov EDX, OFFSET mesg
    call writestring

    call readint
    mov miles, EAX

    mov EDX, OFFSET mesg1
    call writestring

    call readint
    mov gallons, EAX

    mov EDX, OFFSET mesg2
    call writestring

    mov eax, miles
    mov ebx, gallons
    SUB EDX, EDX       <-----what dose this do? because if i didn't do it, i get junk result 

    div ebx
    call writeint
    exit
  main endp
end main
Michael Petch
  • 46,082
  • 8
  • 107
  • 198
Ahmed Hadi
  • 121
  • 1
  • 3
  • 12

1 Answers1

2

Well, it is simple: DIV does divide the 64-bit value of EDX(bits 63-32):EAX(bits 31-0) by the operand of EBX(32-bits).

The sub zeros edx

The general procedure of the DIV instruction is

EDX(higher 32-bit):EAX(lower 32-bit) DIV src-Operand(32-bit) => EAX(32-bit) and remainder in EDX(32-bit)

So in your case of

mov eax, miles
mov ebx, gallons
SUB EDX, EDX       <-----what dose this do? because if i didn't do it, i get junk result 
div ebx

You set EAX to miles, EBX to gallons and then you reset EDX to zero by sub edx,edx(set EDX to 0). So you have

  • EAX=miles
  • EBX=gallons
  • EDX=0

Executing DIV EBX means dividing EDX:EAX(64-bit) by EBX(32-bit). Therefore EDX has to be set to 0 before the execution of the DIV if you're not dividing a 64-bit value.

If EDX would not be 0 at the time of division, it would be included as a part of the 64-bit(EDX:EAX) by 32-bit(EBX) division. This would give a false result. Therefore EDX is set to 0 by SUB EDX, EDX before the div ebx.

I hope that clears it up.

Community
  • 1
  • 1
zx485
  • 28,498
  • 28
  • 50
  • 59