【问题标题】:ForLoop is always returning not_prime Assemblyx86 32bitFor Loop 总是返回非主要程序集 X86 32 位
【发布时间】: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 命令。

标签: c assembly x86 primes


【解决方案1】:

mov ebx, eax; div ebx 将始终为您提供 1,因为您将 eax 自己分开。无论如何,如果您不将其归零,我仍然会在 edx 中,您可以将其复制回来。或者更好的是,不要在 eax 中破坏它,只需将 i*i 放入 edx 或任何地方(即 imul edx,eax)。 ——小丑

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 2014-02-11
    • 2014-08-19
    • 1970-01-01
    • 2013-10-23
    相关资源
    最近更新 更多