gpt4 book ai didi

通过汇编比较 2 个数字

转载 作者:行者123 更新时间:2023-11-30 19:55:37 25 4
gpt4 key购买 nike

我有以下代码。我想完成如下所示的汇编代码:

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;
}

当我们跳过“Hello”时,该程序的输出只是“World”。这是相同的示例,但有比较跳跃:

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;
}

关于通过汇编比较 2 个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14523333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com