1

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

我正在尝试将以下代码从纯 C转换为汇编语言

纯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
4

1 回答 1

2

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

你有 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

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

于 2012-04-19T17:06:19.910 回答