【发布时间】:2016-03-05 23:08:35
【问题描述】:
我对装配很陌生。我们正在使用 32 位程序集 x86。我正在尝试将此 C 代码重构为程序集。
//C code
for (i=2; i*i<=n; i++){
if ((n%i)==0){
is_prime=false;
break;
}
}
//=================================================
;ASSEMBLY CODE
;eax will contain the read in integer
forLoop:
mov edx, eax ; copy eax into edx
imul eax, edx ; multiply eax by edx value stored in eax
mov edx, 0 ; set remainder to 0
cmp eax, ecx ; if eax * eax
jg skip ; if greater than jump to skip.
mov ebx, eax ; move to divide
div ebx ; restore eax
mov edx, 0 ; set divisor to 0
mov ebx, eax ; copy iterator to divisor
push eax ; save iterator
mov eax, ecx ; copy n to numerator
div ebx ; divide EAX/EBX
pop eax ; restore iterator
add eax, 1 ; inc iterator
cmp edx, 0 ; compare divisor to 0
jne forLoop
mov dword [ebp-4], 0
jmp skip
Sample Output
1
not prime
2
prime
3
prime
4
not prime
5
not prime
6
not prime
7
not prime
8
not prime
9
not prime
0
因此,for_loop 是唯一将我的布尔值设置为 false 并将其设置为 print_not_prime 的唯一方法。因此,我认为当我将余数除以 edx 时设置不正确!我很困惑。
【问题讨论】:
-
div ebx ; restore eax我不明白。无论如何,使用调试器来单步调试代码。 -
gotcha,基本上因为我在做 i*i 这个值存储在 eax 中,所以我通过将原始值 i 移动到 ebx 来划分它,然后划分它,所以我在平方之前恢复迭代器它。
-
mov ebx, eax; div ebx将始终为您提供1,因为您将eax自己分开。无论如何,i仍然会在edx中,如果你没有将它归零,你可以把它复制回来。或者更好的是,不要在eax中破坏它,只需将i*i转换为edx或任何地方(即imul edx, eax)。 -
有人知道如何在 gdb 中输入一个数字,这样我就可以真正看到 forloop 中发生了什么??
-
不确定
input是什么意思...您可以设置和打印寄存器,如果您的程序要求在标准输入上输入,您可以输入。如果它需要命令行参数,您可以使用set args或作为参数添加到run甚至gdb --args命令。