assembly – How to do division in ARM?

assembly – How to do division in ARM?

If you just want to divide an integer value in r0 by 9 you can approximate that with:

ldr r3,=0x1C71C71D   # 1C71C71D == (2^32 / 9) + 1
umull   r9,r3,r0,r3

r3 now contains the integer part of the quotient, and r9 contains the fractional part scaled by 2^32. To get the remainder youd just multiply the integer part of the quotient by 9 and subtract the result from the original value.

Michaels answer is right if you divide the number by a constant and you need an integer result. You wont get the fraction part like you want.

If you need a floating-point result youll need a floating-point division function, which is not easy to implement in software and asm on architectures without FPU. ARMv7 and above have FPU/SIMD by default, some ARMv6 and below also have FPU so you can divide it directly in hardware

A fixed-point solution may be easier, just divide the number like normal integer division but remember to adjust the result after calculation. Of course fixed-point number wont have large dynamic range like floating-point but in your case I think the range is enough. You can also multiply the remainder by 10n, with n is the number of digits after decimal sign you need, then divide it with the above divisor again to get the fractional part

For example to get the result of 22/9 with 3 digits of precision do as follow:

22/9   = 2 remains 4
4*10^3 = 4000
4000/9 = 444
→ 22/9 = 2.444

To get more precision, just multiply the remainder with a larger power of 10

assembly – How to do division in ARM?

Leave a Reply

Your email address will not be published.