assemblyx86masmswapirvine32

Use a loop to swap the nth position elements from array1 and array2


I am currently taking an assembly course and I have a homework question I want to make sure is correct. My question states:

Give an array named array1 with the values 1000h, 2000h, 3000h, 4000h, 5000h and another array named array2 with the values 11111h, 22222h, 33333h, 44444h, 55555h. Use a loop to swap the nth position elements from array1 and array2.

I wrote this code:

; AddTwo.asm - adds two 32-bit integers.
; Chapter 3 example

.386
.model flat,stdcall
.stack 4096
INCLUDE Irvine32.inc ; including the library onto the program
ExitProcess proto,dwExitCode:dword

.data
    array1 WORD 1000h, 2000h, 3000h, 4000h, 5000h
    array2 DWORD 11111h, 22222h, 33333h, 44444h, 55555h

.code
main proc
    mov ecx, 5
    mov esi, offset Array1 ; esi points to beginning of Array1
    mov edi, offset Array2
L1:
    xchg edi, esi ; swaps values of array1 (esi) and array2 (edi)

    add esi, 4 ; increments the address to next element
    add edi, 4
    loop L1 ; will loop through label 1 amount of times ecx is




    call DumpRegs ; main utility call to display all registers and status flags
    invoke ExitProcess,0
main endp
end main

My code compiles, but I am not 100% certain if this correct. Any help will be greatly appreciated.


Solution

  • array1 WORD 1000h, 2000h, 3000h, 4000h, 5000h
    array2 DWORD 11111h, 22222h, 33333h, 44444h, 55555h
    

    If you want a chance of a succesful swap then you need to define both arrays of the same size. How could you store a DWORD in a WORD-sized location?

    Don't choose a data format based on the example numbers that you got, but rather base your selection on what your program is supposed to achieve.

    xchg edi, esi ; swaps values of array1 (esi) and array2 (edi)
    

    This only swaps the pointers, not the data that they refer to!

    Next code does swap 2 DWORD sized elements:

    mov eax, [esi]
    mov edx, [edi]
    mov [esi], edx
    mov [edi], eax
    

    As an optimization you should replace the loop L1 instruction by

    dec ecx
    jnz L1
    

    It's faster!