如何用汇编语言编写模数(C++中的%)

use*_*164 0 c++ assembly

我不知道为了翻译%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;
 }
Run Code Online (Sandbox Code Playgroud)

Jer*_*fin 6

在典型的汇编语言中,整数除法指令也会给出余数.在余数除以2的情况下,通过AND位0 转换为逐位更容易.例如,在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
Run Code Online (Sandbox Code Playgroud)

如果需要通过某个任意数字(而不是仅仅2)检查可除性,则除法指令通常会产生商和余数.再次,使用x86作为演示:

idiv ebx  ; divisor in edx:eax
; quotient in eax, remainder in edx
Run Code Online (Sandbox Code Playgroud)