X86 assembly – Handling the IDIV instruction

The first part of Mysticials answer is correct, idiv does a 128/64 bit division, so the value of rdx, which holds the upper 64 bit from the dividend must not contain a random value. But a zero extension is the wrong way to go.

As you have signed variables, you need to sign extend rax to rdx:rax. There is a specific instruction for this, cqto (convert quad to oct) in AT&T and cqo in Intel syntax. AFAIK newer versions of gas accept both names.

movq    %rdx, %rbx
cqto                  # sign extend rax to rdx:rax
idivq   %rbx

Leave a Comment