[英]How to write modulus (% in C++) in assembly language
我不知道我必须使用什么指令来翻译%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;
}
在典型的汇编语言中,整数除法指令还会为您提供余数。 对于除数为2的余数,将其转换为与位0的按位AND
要容易得多。 例如,在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
如果您需要检查任意数(而不是2)的可除性,除法指令通常会同时产生商和余数。 同样,以x86为例:
idiv ebx ; divisor in edx:eax
; quotient in eax, remainder in edx
模数通常由除法指令产生。 但是,取模2、4、8、16等为一个特殊情况:因为数字以二进制形式存储,所以可以使用AND
指令进行这些检查。
检查2除数的最快方法是查看值的最低有效位。 使用AND
指令,其值为1
,即number & 1
。 其结果始终与number % 2
相同。 大多数现代的编译器(和一些古老的编译器)都会将其作为一种简单的优化方法。
对于其他2的幂, AND
值减去1,即对于x % 4
使用x & 3
,对于x % 8
使用x & 7
,依此类推。
在没有一点测试指令的汇编语言中,您将必须(布尔)与值进行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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.