Reversing an array in assembly

蓝咒 提交于 2019-12-06 11:26:52

In general it's best to imagine it as 2 pointers. The first pointer begins at the start of the array and moves towards the end, and the second pointer begins at the end of the array and moves towards the start.

If there are an even number of items in the array, eventually start will be higher than end. If there are an odd number of items in the array, eventually start will be equal to end. Basically, in C you'd be looking for something like while(start < end) { ... }.

For assembly (NASM syntax), this might look a bit like this:

;Reverse array of 32-bit "things" (integers, pointers, whatever)
;
;Input
; esi = address of array
; ecx = number of entries in array

reverseArrayOf32bit:
    lea edi,[esi+ecx*4-4]      ;edi = address of last entry
    cmp esi,edi                ;Is it a tiny array (zero or 1 entry)?
    jnb .done                  ; yes, it's done aleady

.next:
    mov eax,[esi]              ;eax = value at start
    mov ebx,[edi]              ;ebx = value at end
    mov [edi],eax              ;Store value from start at end
    mov [esi],ebx              ;Store value from end at start

    add esi,4                  ;esi = address of next item at start
    sub edi,4                  ;edi = address of next item at end
    cmp esi,edi                ;Have we reached the middle?
    jb .next                   ; no, keep going

.done:
    ret
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!