0

I am making a simple program to convert hexadecimal numbers to decimal through repeated division method.

xor rbx,rbx
xor rdx,rdx
mov bx,0Ah
divide:
div bx
flag11:
push rdx
dec r8
jnz divide

The input given was 1234.The value in rax after conversion from ascii to hex was

rax            0x1234   4660

which is correct.The division process went smoothly for the first two runs,but after the third division,this is what happened:

rax            0x999e   39326

Insted of a 4,there's a random value in the register.Why is this happening and how can I fix it?

  • 1
    maybe see this http://stackoverflow.com/questions/8858104/64bit-nasm-division-idiv – ralf htp Apr 09 '16 at 13:43
  • 1
    You need to zero `dx` inside the loop. – Jester Apr 09 '16 at 14:16
  • @Jester - Thanks,that worked!Can you explain why manual zeroing was required?Shouldn't the div operation overwrite the previous value?And why does it change the value in rax? –  Apr 09 '16 at 14:18
  • 3
    Read how `div` works in an instruction set reference. TL:DR: it uses `dx` as the top half of the dividend, so it should be zeroed if your dividend doesn't need it. – Jester Apr 09 '16 at 14:23
  • Your [_DIV_](http://www.tptp.cc/mirrors/siyobik.info/instruction/DIV.html) has the side effect of placing the remainder into DX. It has to be cleared manually in the loop otherwise the remainder of the previous DIV would be fed into the next division as the upper part of the dividend which is not what you want. – Michael Petch Apr 09 '16 at 14:50
  • Ahh I see.Thanks for the answers. –  Apr 10 '16 at 14:52

0 Answers0