user3019164
user3019164

Reputation: 29

How to write modulus (% in C++) in assembly language

I do not know what instruction I have to use in order to translate %2

#include <iostream>
using namespace std;

int main () {
     int number;
     cin >> number;
     if (number % 2 == 0) {    // I cannot translate this part.
       cout << "Even\n";
    }
    else {
       cout << "Odd\n";
    }
    return 0;
 }

Upvotes: 0

Views: 14112

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490278

In a typical assembly language, the integer divide instruction will also give you the remainder. In the case of remainder when dividing by 2, it's a lot easier to translate to a bit-wise AND with bit 0 though. E.g., on x86:

    mov eax, number

    ; test sets the flags based on a bitwise and, but discards the result
    test eax, 1

    mov esi, offset even_string
    jz print_it
    mov esi, offset odd_string
print_it:
    ; print string whose base address is in esi

If you need to check for divisibility by some arbitrary number (instead of just 2), the division instruction will usually produce both the quotient and the remainder. Again, using x86 as a demonstration:

idiv ebx  ; divisor in edx:eax
; quotient in eax, remainder in edx

Upvotes: 6

Thomas Matthews
Thomas Matthews

Reputation: 57728

In assembly languages that don't have a bit test instruction, you will have to (Boolean) AND the value with 1:

    LODI, R0  #5    ; Load register 0 with the number 5.
    ANDI, R0  #1    ; Boolean AND the register with one (1).
    JUMZ      Value_is_even; jump if the value is zero.
;
;   Go here if the value is odd.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726779

Modulo is typically produced by the division instruction. However, taking modulo 2, 4, 8, 16, and so on is a special case: because the numbers are stored in the binary form, these checks can be done with an AND instruction.

The fastest way of checking divisibility by 2 is looking at the least significant bit of a value. Use AND instruction with the value of 1, i.e. number & 1. Its result is always the same as number % 2. Most modern compilers (and some archaic ones) will do this as an easy optimization.

For other powers of two, AND with that value minus one, i.e. for x % 4 use x & 3, for x % 8 use x & 7, and so on.

Upvotes: 2

Related Questions