Rick Dearman
Rick Dearman

Reputation: 386

Finding the modulo with GAS ARM assembler

I'm attempting to find the remainder in GAS assembler on an ARM processor. Looking that the arm documentation it seems to have this instruction, but I can't seem to make it work using gas. Anyone know if this is valid, and what the syntax is?

mov r3, [r9] MOD #2

I'm basically wanting to load register 3 with the modulo from division of the contents of register 9 by 2.

Previously I wrote a separate subroutine doing the subtraction and calculation myself, but the arm website seems to show this as a valid instruction.

https://www.keil.com/support/man/docs/a51/a51_op_mod.htm

Upvotes: 1

Views: 210

Answers (1)

Nate Eldredge
Nate Eldredge

Reputation: 58493

The MOD you're looking at is an operator in the assembler; it can be used to compute the MOD function of constants at assembly time, so that you can use the result as another constant. It is not a machine instruction, and is of no use in computing things for values that are not known until run time.

Computing a remainder mod 2 is very easy; simply find the logical AND with the number 1.

and r3, r9, #1

If using Thumb, you need two instructions:

movs r3, #1
ands r3, r9

For a divisor b which is not a constant power of 2, finding a mod b is harder. You take advantage of the fact that a mod b = a - ((a/b)*b). Use SDIV to find the quotient a/b, then MLS to multiply it by b and subtract from a.

Upvotes: 1

Related Questions