gpt4 book ai didi

c++ - ASM at&t 语法

转载 作者:行者123 更新时间:2023-11-28 03:00:23 24 4
gpt4 key购买 nike

所以我对这段代码有疑问。这是一个将二进制数转换为十进制数的程序。

#include <cstdlib>
#include <iostream>
#include <cstdio>

char s[100];
int length;
int a;


int main(int argc, char *argv[])
{

system("cls");
printf("\n\n Vvedite stroky iz 0 i 1 (do 8 delementov) > ");
gets(s);

asm("leal s,%esi");
asm("movl 8,%ecx");
asm("movl 0,%edx");
asm("repeat:");
asm("movl 1,%eax");
asm("dec %ecx");
asm("rol %cl,%eax");
asm("cmpb 31,%esi");
asm("jnz x");
asm("add %eax,%edx");
asm("x: inc %esi");
asm("cmpb 0,$esi");
asm("jnz repeat");
asm("movl %edx,a");

printf("4islo %d",a);

return EXIT_SUCCESS;
}

它给了我:“段错误(核心已转储)”

请帮助完成此 ASM 部分。我认为是 CMPB 运营商的问题。

最佳答案

该代码存在一些问题 - 在我的系统上,它甚至没有通过编译器/汇编器运行。主要问题是您需要在所有文字前加上 $ 前缀,否则汇编程序会假定内存访问:

asm("movl 8,%ecx"); // tries to access memory at address 8 => Segmentation fault

这是必须的

asm("movl $8,%ecx"); // Moves literal 8 into ecx

相应地调整所有其他说明。

另一个问题是下面的指令:

asm("cmpb 0,$esi");   // $esi is not a literal nor a register name

这是必须的

asm("cmpb $0,(%esi)");  // compare value at address stored in %esi with literal 0 (end of string)

我建议你编译带有调试信息的代码,比如

$ g++ -g -o sample sample.c

调试程序就很容易了:

$ gdb sample 
(gdb) run
Starting program: sample
sh: cls: command not found

Vvedite stroky iz 0 i 1 (do 8 delementov) > 10101010

Program received signal SIGSEGV, Segmentation fault.
main (argc=1, argv=0x7fffffffe238) at sample.c:18
18 asm("movl 8,%ecx"); // current bit position

如您所见,调试器向您显示了导致段错误的指令。

更新

对我有用的汇编代码,使用 @Brett 建议的单个 asm 语句:

asm("leal s, %esi         \n\t"   // s => %esi
"movl $8, %ecx \n\t" // current bit position (+1)
"movl $0, %edx \n" // initialize result

"repeat: \n\t"
"movl $1, %eax \n\t" // Create bit mask in %eax
"dec %ecx \n\t" // Decrement rotation counter to shift mask bit to proper position
"rol %cl, %eax \n\t" // calculate value of current binary digit

"cmpb $0x31, (%esi) \n\t" // current digit == 1?
"jnz x \n\t" // no, skip
"add %eax, %edx \n" // add current value to %edx

"x: \n\t"
"inc %esi \n\t" // next address in input string
"cmpb $0, (%esi) \n\t" // end of string reached?
"jnz repeat \n\t" // no, continue

"movl %edx,a \n"); // store result in a variable
$ ./sample 

Vvedite stroky iz 0 i 1 (do 8 delementov) > 10101010
4islo 170

关于c++ - ASM at&t 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21000054/

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