Modulo in assembly

How to implement modulo in ARM assembly???
Tom3333Asked:
Who is Participating?
 
Dave BaldwinConnect With a Mentor Fixer of ProblemsCommented:
Here's a little pseudo code.  This does not account for negative numbers as input.
; psuedo code...
mov a,dividend  ; the number to be divided
mov b,divisor   ; the number to divide by

loop:
sub a,b   ;subtract b from a
jmp positive, loop  ; do it again until the result is not positive

; if negative result, add it back Once
add a,b  ; and we're done

Open in new window

1
 
Dave BaldwinFixer of ProblemsCommented:
0
 
Tom3333Author Commented:
Hello DaveBaldwin i  mean to implement modulo with out use command MOD. Do you have any resources about this ?
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
Dave BaldwinFixer of ProblemsCommented:
The last time I saw a routine for that, they just subtracted the divisor until the result went negative and then they added it back once.
1
 
Tom3333Author Commented:
Hello DaveBaldwin,
can you give the code or the pseudo-code for this???
0
 
Conrad SabatierCommented:
Here's some Bourne (again) shell code that illustrates two easy ways to implement a MOD function.

The first uses the method described in another reply to your question, subtracting the divisor from the dividend until the result is less than or equal to zero.  If less than zero, add the divisor back once to get the final result,  else the result is, of course, zero.

function mod
#
#       Perform the arithmetic operation
#       "$1 mod $2", without using the
#       shell's builtin "%" operator
#
#############################
{
        mod=$1

        until ((mod <= 0))
        do
                ((mod -= $2))
        done

        ((mod < 0)) && ((mod += $2))

        echo $mod
}

The second simply does a division, then subtracts (quotient * divisor) from the original number (dividend).  This assumes, of course, the presence of both the ARM "udiv" and "mul" instructions:

function mod
#
#       (An alternate version)
#
#       Perform the arithmetic operation
#       "$1 mod $2", without using the
#       shell's builtin "%" operator
#
#############################
{
        quotient=$(($1 / $2))
        mod=$(($1 - ($2 * quotient)))

        echo $mod
}

The translation from shell code to ARM assembly language is simple and straightforward enough that I leave it as an exercise for the reader.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.