Division

The following shows how to do signed division on the most popular CPU architectures.

x86-64

The idiv instruction expects the 128-bit dividend to be in the hardcoded registers r2:r0 and the divisor inside a register or memory location. It stores the result in r0 and the remainder in r2. The cqo instruction sign-extends r0 to r2.

Assembly:

cqo
idiv r1

Machine code:

48 99
48 F7 F9

Pseudo code:

r2 = extend(r0)
tmp = r2:r0
r0 = tmp / r1
r2 = tmp % r1

arm64

The sdiv instruction expects a destination register, the dividend register and a divisor register.

Assembly:

sdiv x0, x1, x2

Machine code:

9A C2 0C 20

Pseudocode:

x0 = x1 / x2

It does not compute the remainder, but it can be computed with an extra msub which will multiply the quotient with the divisor and subtract the result from the dividend, giving us the remainder.

Assembly:

msub x3, x0, x2, x1

Machine code:

03 84 02 9B

Pseudocode:

x3 = x1 - (x0 * x2)

riscv64

Assembly:

div a0, a1, a2

Machine code:

33 C5 C5 02

Pseudocode:

a0 = a1 / a2

The manual states that if the remainder is needed, an extra rem instruction should be placed immediately after because microarchitectures can then fuse these into a single divide operation instead of performing two separate divides.