Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one do integer (signed or unsigned) division on ARM?

I'm working on Cortex-A8 and Cortex-A9 in particular. I know that some architectures don't come with integer division, but what is the best way to do it other than convert to float, divide, convert to integer? Or is that indeed the best solution?

Cheers! = )

like image 506
Phonon Avatar asked Dec 01 '11 20:12

Phonon


People also ask

Which instructions is used for signed division?

The DIV (Divide) instruction is used for unsigned data and the IDIV (Integer Divide) is used for signed data.

What is UDIV in ARM assembly?

UDIV performs an unsigned integer division of the value in Rn by the value in Rm . For both instructions, if the value in Rn is not divisible by the value in Rm , the result is rounded towards zero.


2 Answers

Division by a constant value is done quickly by doing a 64bit-multiply and shift-right, for example, like this:

LDR     R3, =0xA151C331
UMULL   R3, R2, R1, R3
MOV     R0, R2,LSR#10

here R1 is divided by 1625. The calculation is done like this: 64bitreg(R2:R3) = R1*0xA151C331, then the result is the upper 32bit right shifted by 10:

R1*0xA151C331/2^(32+10) = R1*0.00061538461545751488 = R1/1624.99999980

You can calculate your own constants from this formula:

x / N ==  (x*A)/2^(32+n)   -->       A = 2^(32+n)/N

select the largest n, for which A < 2^32

like image 63
Willem Hengeveld Avatar answered Sep 19 '22 22:09

Willem Hengeveld


Some copy-pasta from elsewhere for an integer divide: Basically, 3 instructions per bit. From this website, though I've seen it many other places as well. This site also has a nice version which may be faster in general.


@ Entry  r0: numerator (lo) must be signed positive
@        r2: deniminator (den) must be non-zero and signed negative
idiv:
        lo .req r0; hi .req r1; den .req r2
        mov hi, #0 @ hi = 0
        adds lo, lo, lo
        .rept 32 @ repeat 32 times
          adcs hi, den, hi, lsl #1
          subcc hi, hi, den
          adcs lo, lo, lo
        .endr
        mov pc, lr @ return
@ Exit   r0: quotient (lo)
@        r1: remainder (hi)
like image 38
Michael Dorgan Avatar answered Sep 21 '22 22:09

Michael Dorgan