4

In my program, a hex number is divided by ten and the remainder is checked.

First division is performed well; however, after the second division, the program goes wrong. I am new to assembly, and I couldn't find where the problem is...

Here is the code segment:

ORG 1000

    MOV AX, 0x04B4 (1204 decimal value )
    MOV BX, 0x000A ( 10 decimal value )
    MOV CX, 0x0000

    DIV BX ( After this part, AX is 120 decimal and DX 4 decimal )

    CMP DX, 0x0000
    JE eq1

    ADD CX, 0x0002
    JMP con1

    eq1:    ADD CX, 0x0001  

    con1:

    DIV BX ( But, after this division AX becomes 6677 ( 26231 decimal and DX remains 4 decimal )
    CMP DX, 0x0000

Thanks for help!

hmakholm left over Monica
  • 23,074
  • 3
  • 51
  • 73
ciyo
  • 725
  • 4
  • 16
  • 36
  • This could be the single most common assembly question. Can't something be done about that? If you make a new question, the suggestionbox contains mostly questions of the form "integer division didn't return a float, I'm so confused" and the ones of the form "I forgot that `div` is double-width" don't really show up. – harold Oct 23 '12 at 11:46

2 Answers2

12

The DIV BX instruction divides the 32-bit value in DX:AX by BX. Since you're not initializing DX, the upper word of the dividend is whatever garbage was left in the DX register from the previous computation, so you're really dividing 0x00040078=262314 by 10. The result is correct: a quotient of 26231 with a remainder of 4.

In the first division is must have been pure luck that DX happened to be 0 initially.

Paul R
  • 208,748
  • 37
  • 389
  • 560
hmakholm left over Monica
  • 23,074
  • 3
  • 51
  • 73
3

Intel instruction DIV divides the register pair DX:AX with the argument.

In the first case DX happens to be zero.
The second time DX must have been 4.

Aki Suihkonen
  • 19,144
  • 1
  • 36
  • 57