比较2个数字与汇编
我有以下代码。 我想完成汇编代码,如下所示:
int main(void) { int x = 10; int i=0; label1: asm (.....) // code to add here: if i>=x then jump to label2 printf("%d\n",i); i++; asm (.....) // code to add here: jump to label 1 label2: printf("out\n"); }
我的机器是x86,操作系统是Ubuntu 12
首先,给自己一个x86操作码列表,应该很容易在网上找到。
asm()
函数遵循以下顺序:
asm ( "assembly code" : output operands /* optional */ : input operands /* optional */ : list of clobbered registers /* optional */ );
其次,你遇到的一个主要问题是你不能“跳转”到C标签,你需要使你的标签成为一个“组装”标签,以便能够跳转到它。 例如:
int main() { asm("jmp .end"); // make a call to jmp there printf("Hello "); asm(".end:"); //make a "jumpable" label printf("World\n"); return 0; }
当我们跳过“你好”时,这个程序的输出就是“世界”。 这是相同的例子,但有一个比较性的跳跃:
int main() { int x = 5, i = 0; asm(".start:"); asm("cmp %0, %1;" // compare input 1 to 2 "jge .end;" // if i >= x, jump to .end : // no output from this code : "r" (x), "r" (i)); // input's are var x and i printf("Hello "); i++; asm("jmp .start;"); asm(".end:"); printf("World\n"); return 0; }
如果您不是真的必须在这里使用汇编,那么您可以更轻松地使用C,并且至少与汇编版本一样有效:
int x = 10; int i = 0; while(i < x) { printf("%d\n",i); i++; } printf("out\n");
( for
-loop也适合)
我不记得在c中使用汇编程序的语义,但通常当你比较汇编程序中的数字时,你会相互减去数字。 如果它们是相同的数字,则将设置零位,因此您可以进行条件跳转。 一定要使用正确的寄存器来匹配int的大小。
非常粗略的示例代码(这是我的头脑,我写了汇编程序已经多年了):
#load value to compare against into BX #load number to check into AX CMP AX, BX JE label
更新:根据@harold的建议将SUB更改为CMP