How to do the modulo operation in ARM assembly?

arm
16,639

Not all ARM processors have a direct instruction for division or modulo, so in most cases, a call to the modulo operation would end up as a function call to e.g. ___modsi3.

In this particular case, when doing modulo for 8, if the values can be assumed to be nonnegative, you can do the % 8 part as & 7. In that case, the assembly for your case would be:

add rA, rA, rB
and rC, rA, #7
Share:
16,639
Shrey
Author by

Shrey

By Day: i'm usually in school doing college assignments or scouring the internet for interesting happenings in tech world. By night: Usually cook and watch some hackathons to be aware of how vulnerable we are even after being so secure. Passionate about being a future software engineer. Love to solve problems with different approaches and build something from scratch.

Updated on December 02, 2022

Comments

  • Shrey
    Shrey over 1 year

    I'm trying to add the values in two registers, and modulo them by 8. So, in C code, it would be like this

    a = a + b;
    c = a % 8;
    

    how to do this above operation in ARM assembly.

  • InfinitelyManic
    InfinitelyManic about 7 years
    What case is this assuming since it fails for certain values; e.g., 71 mod 15 = 6 test=11. Unless I'm missing something.
  • old_timer
    old_timer about 7 years
    modulo 8 is an and with 7, because 8 is a power of 2. but modulo 15 is a completely different thing you cant use base 2 and operations you have to actually divide.
  • InfinitelyManic
    InfinitelyManic about 7 years
    @old_timer, yeah I assumed that may have been the case. I have used a subtraction based mod function; however, it's much slower than a div (where available) based mod function due to the loops.