【问题标题】:Sort an array via x86 Assembly (embedded in C++)?? Possible?通过 x86 程序集(嵌入在 C++ 中)对数组进行排序??可能的?
【发布时间】:2011-02-08 06:10:47
【问题描述】:

我第一次玩 x86 汇编,但我不知道如何对数组进行排序(通过插入排序)。我了解算法,但汇编让我感到困惑,因为我主要使用 Java 和 C++ .这就是我目前所拥有的一切

int ascending_sort( char arrayOfLetters[], int arraySize )
{
 char temp;

 __asm{

     push eax
     push ebx
      push ecx
     push edx
    push esi
    push edi

//// ???

    pop edi
    pop esi
       pop edx
    pop ecx
     pop ebx
    pop eax
 }
}

基本上没有 :( 有什么想法吗??提前致谢。

好的,这只会让我听起来像个白痴,但我什至无法更改 _asm 中的任何数组值

只是为了测试一下,我放了:

mov temp, 'X'
mov al, temp
mov arrayOfLetters[0], temp

这给了我一个错误 C2415:不正确的操作数类型

所以我尝试了:

mov temp, 'X'
mov al, temp
mov BYTE PTR arrayOfLetters[0], al

这符合,但它没有改变数组...

【问题讨论】:

  • 作为开始,您可以反过来尝试。用 C/C++ 实现你的函数并研究编译器为你生成的汇编代码。只是为了得到一个印象......
  • 第一步是用C++编写排序算法。然后尝试将循环转换为等效的汇编代码。
  • 嗯,会试试的,谢谢!不,不是,我已经迷失了大约 6 个月的业余爱好者:/
  • 使用汇编程序编写插入排序当然是可能的。我的 C++ 编译器每天都会这样做。你真正需要什么样的帮助?你想知道如何传递参数或其他东西吗?
  • @paxdiablo,来吧,将模板化的多态类转换为程序集有多难?

标签: c++ assembly x86 insertion-sort


【解决方案1】:

此代码现在已经过测试。我把它写在记事本中,它没有一个很好的调试器,我想不到。然而,这应该是一个很好的起点:

mov edx, 1                                  // outer loop counter

outer_loop:                                 // start of outer loop
  cmp edx, length                           // compare edx to the length of the array
  jge end_outer                             // exit the loop if edx >= length of array

  movzx eax, BYTE PTR arrayOfLetters[edx]   // get the next byte in the array
  mov ecx, edx                              // inner loop counter
  sub ecx, 1

  inner_loop:                               // start of inner loop
    cmp eax, BYTE PTR arrayOfLetters[ecx]   // compare the current byte to the next one
    jg end_inner                            // if it's greater, no need to sort

    add ecx, 1                              // If it's not greater, swap this byte
    movzx ebx, BYTE PTR arrayOfLetters[ecx] // with the next one in the array
    sub ecx, 1
    mov BYTE PTR arrayOfLetters[ecx], bl
    sub ecx, 1                              // loop backwards in the array
    jnz inner_loop                          // while the counter is not zero

  end_inner:                                // end of the inner loop

  add ecx, 1                                // store the current value
  mov BYTE PTR arrayOfLetters[ecx], al      // in the sorted position in the array
  add edx, 1                                // advance to the next byte in the array
  jmp outer_loop                            // loop

end_outer:                                  // end of outer loop

如果您对 DWORD 值(int)而不是 BYTE 值(字符)进行排序,这会容易得多。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多