【问题标题】:Insertion Sort assembly code (Translated from C)插入排序汇编代码(从C翻译而来)
【发布时间】:2012-04-16 23:27:44
【问题描述】:

我对汇编编程没有深入的了解。

我正在尝试将以下代码从 Pure C 翻译成 Assembly 语言

纯 C

int i,j,temp;
for ( i = 0 ; i < 10 ; i++ )
{
    temp = global_array[i];
    for ( j = i-1 ; j >= 0 ; j-- )
    {
        if ( global_array[j] <= temp ) break; //if first value is bigger than the second value
            global_array[j+1] = global_array[j];
    }
    global_array[j+1]=temp;
}

请检查我从纯 C 语言到汇编语言的翻译效果如何?

ASM

.globl _Sort
//.type AtoI,@function

//Declaration of variables
.comm _global_array,40 //this is an array of integers
.comm _temp,4 //this is the variable temp
.comm _i,4 //used for loop
.comm _j,4 //used for loop



_Sort:
/*prolog*/
pushl %ebp
pushl %ebx
movl %esp, %ebp //move the special ptr to base ptr
subl $8, %esp //allocate space for the variables local_var and temp_var

pushl %esi //index register
pushl %edi //index register


/*put code here*/
//for ( i = 0 ; i < 10 ; i++ )
//first for loop
movl $0, _i //index i = 0

ForOne:
movl _i, %eax
movl _i, %esi //move i into index register
cmp $10, %eax //if i is less than or equal 9, continue this loop
jge return
movl _global_array, %ebx
movl (%ebx,%esi,4), _%ecx
movl %ecx, _temp //temp = global_array[i]
movl _i, %eax //i-1
subl $1, %eax
movl %eax, _j //move j into index register
jmp ForTwo //jump to second for loop

ForTwo:
movl _j, %eax
cmp $0, %eax //j >= 0
jl ForOneFn //get out of 2nd loop to end of 1st loop
movl _global_array, %ebx
cmp _temp, (%ebx,%edi,4) //if ( global_array[j] <= temp ) break;
jle ForOneFn //jump to end of first loop after break
movl (%ebx,%edi,4),%ecx
addl $1,%eax //j+1
movl _j, %edi //move j into index register 
movl _global_array, %ebx
movl %ecx, (%ebx,%edi,4) //global_array[j+1] = global_array[j];

//last line of code is jump to reloop/finish 2nd loop
jmp ForTwoFn

ForTwoFn:
subl $1, _j
jmp ForTwo

ForOneFn:
addl $1, _i
jmp ForOne


return:
/*epilog*/
movl %ebp,%esp
popl %ebx
popl %ebp
ret

【问题讨论】:

  • 问题是,你试过了吗?它有效吗?如果不是,那是什么行为?
  • 您遇到了什么具体问题?
  • 同样重要的是,C 代码还能工作吗?第 8 行缩进,使其看起来属于第 7 行的 if 块,但实际上并非如此。
  • @AaronDufour 那里的代码是正确的,缩进不是。
  • 它不起作用,因为我面临一些编译问题,例如对 'mov' 的内存引用过多......我希望我能在我的数组代码中找到一些错误......

标签: c algorithm sorting assembly insertion-sort


【解决方案1】:

第一个建议:更密集地使用寄存器。

你有2个索引变量,临时变量和global_array地址,所以你有足够的寄存器。

代码应该编译如果行:

cmp _temp, (%ebx,%edi,4) //if ( global_array[j] <= temp ) break;

将被替换为:

cmp eax, (%ebx,%edi,4) //if ( global_array[j] <= temp ) break;, where eax is yours temp

如果你只使用寄存器来编写这个例程,它会更小,更容易理解和调试。

【讨论】:

  • 谢谢!我现在设法编译它。但是我收到总线错误。你知道怎么解决吗?
  • 可能您的索引(i 或 j)变量之一超出数组范围(超出下限、0 或上限)并且您的代码访问了不属于程序的内存。我建议验证循环索引佣金和条件跳转。
猜你喜欢
  • 1970-01-01
  • 2021-08-16
  • 2012-10-17
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 2022-12-20
  • 2016-02-10
  • 1970-01-01
相关资源
最近更新 更多