比较内联c汇编中的数字

时间:2013-11-15 23:52:05

标签: c gcc assembly x86 inline-assembly

我正试图在c中感受内联汇编,我之前从未做过任何汇编编程,所以我试图将随机代码片段转换为汇编代码。 我在下面的代码中遇到了问题,如果a低于此值,我希望它返回0x20(32) 0x20(32)或高于0x7e(126)。 (那是不可打印的字符)然而它也会变成字符 在这些数字之间变成0x20(32)

#include <stdio.h>
int foo(int a) {
  asm (
    "mov $0x20, %%ebx;"
    "cmp %%eax, %%ebx;"
    "jl l1;"
    "mov $0x7e, %%ebx;"
    "cmp %%eax, %%ebx;"
    "jg l1;"
    "jmp l2;"
    "l1: movl $0x20, %%eax;"
    "l2:;"

    : "=a" (a)
    : "a" (a)
    : "%ebx"
  );
  return a;
}
int main(void) {
  int i;
  for (i = 0; i <= 255; i++) {
    printf("%i: %i\n", i, foo(i));
  }
}

此输出
0:32
1:32
2:32
...
31:32
32:32
33:32
34:32
35:32
...
125:32
126:32
127:32
128:32
...

2 个答案:

答案 0 :(得分:1)

由于您未指定 else

,代码将返回32
  ...
  asm (
    "mov $0x20, %%ebx;"
    "cmp %%eax, %%ebx;" // the order should be ebx, eax
    "jl l1;"
    "mov $0x7e, %%ebx;"
    "cmp %%eax, %%ebx;" // the order should be ebx, eax
    "jg l1;"
                        // missing step here
    "jmp l2;"
    "l1: movl $0x20, %%eax;"
    "l2:;"
  ...

您无法告诉编译器将存储变量a的位置,您只是将a传递给asm。您可以将其修复为:

#include <stdio.h>
int foo(int a) {
  asm (
    "cmp $0x20, %%eax;"
    "jl l1;"
    "cmp $0x7e, %%eax;"
    "jg l1;"
    "movl $0, %%eax;"   // what should a be otherwise? 0?
    "jmp l2;"
    "l1: movl $0x20, %%eax;"
    "l2:;"

    : "=a" (a)
    : "a" (a)
    : "%ebx"
  );
  return a;
}
int main(void) {
  int i;
  for (i = 0; i <= 255; i++) {
    printf("%i: %i\n", i, foo(i));
  }
  return 0;
}

或:

#include <stdio.h>
int foo(int a) {
  asm (
    "cmp  $0x20, %0;"  // %0 => a
    "jl   l1;"
    "cmp  $0x7e, %0;"  // %0 => a
    "jg   l1;"
    "movl $0, %1;"     // what should a be otherwise? 0?
    "jmp  l2;"
    "l1:"
    "movl $0x20, %0;"  // %0 = a = 0x20
    "l2:;"
    : "=r" (a) // use r(egister)
    : "r" (a)
    :
  );
  return a;
}
int main(void) {
  int i;
  for (i = 0; i <= 255; i++) {
    printf("%i: %i\n", i, foo(i));
  }
  return 0;
}

答案 1 :(得分:0)

我认为你很亲密。也许this HOWTO可以帮到你。

基本上,你有逻辑错误:

#include <stdio.h>
int foo(int a) {
  asm(
    "mov $0x20, %%edx\n\t" // I use %edx because it optimizes better.
    "cmp %1, %%edx\n\t"    // I use %1 because that's more flexible.
    "jg l1\n\t"            // jg here, not jl!
    "mov $0x7e, %%edx\n\t"
    "cmp %1, %%edx\n\t"
    "jl l1\n\t"            // jl here, not jg!
    "jmp l2\n\t"
    "l1: movl $0x20, %0\n\t" // move the result to 0
    "l2:\n\t"

    : "=a" (a) // output
    : "0" (a) // input is the same
    : "%edx" // what is clobbered
  );
  return a;
}
int main(void) {
  int i;
  for (i = 0; i <= 255; i++) {
    printf("%i: %i\n", i, foo(i));
  }
}