sshilovsky
sshilovsky

Reputation: 998

What is the shortest way to divide 2 32-bit signed integers?

I have two 32-bit signed integers in EAX and EBX respectively. If I do:

xor EDX, EDX
idiv EBX

Then, EAX is treated as unsigned 32-bit, and that's wrong. MOVSX doesn't seem to be able to extend sing bit from EAX to EDX:EAX. I also tried to play with CMP and SBC, but I wasn't able to find a solution.

I'd like to know the shortest possible code to do it, or at least code which avoids jumps.

Upvotes: 1

Views: 1545

Answers (2)

Levente Kurusa
Levente Kurusa

Reputation: 1866

It doesn't get converted. idiv is signed divison, which divides the 64 bit value of edx:eax by the operand of idiv, placing the remainder to edx and the quotient to eax. I cannot think of any faster way, than this. If you really think it gets converted somehow, try the CDQ instruction. It does the following:

Sign-extends EAX into EDX, forming the quad-word EDX:EAX. Since (I)DIV uses EDX:EAX as its input, CDQ must be called after setting EAX if EDX is not manually initialized (as in 64/32 division) before (I)DIV.

Upvotes: 5

Nils Pipenbrinck
Nils Pipenbrinck

Reputation: 86313

There is an instruction for that:

CDQ

It sign-extends the 32 bit value stored in EAX to a 64 bit register pair EDX:EAX. This is exactly that register-pair that is the argument for the IDIV instructions.

Your code would look like this:

  CDQ
  IDIV EBX

Here is more information about that instruction:

http://faydoc.tripod.com/cpu/cdq.htm

Upvotes: 3

Related Questions