Search code examples
arraysloopsassemblymasmirvine32

Changing the offset of edi vs changing the value at the address?


So, this is maybe a bit of a specific question, but my ASM assignment is to create a 10 element array that adds the first element to the last one and places the result in the first element of the array, then the second element with the 9th one and places the result in the second element of the array, etc.

a0 + a9 ---> a0 a1 + a8 ---> a1, etc.

The same procedure should subtract the first element from the 10th element and place the result in the 10th element. Subtract the 2nd element from the 9th one and place the result in the 9th element, etc. Like this:

So that if you input 1,2,3,4,5,6,7,8,9,0, as an example, the program output should be 1, 11, 11, 11, 11, 1, 3, 5, 7, -1.

I am at a complete loss here, I'm not sure how to go back and forth moving around the OFFSET in the edi as well as changing the value at that address ?

 INCLUDE c:\Irvine\Irvine32.inc

 ExitProcess proto,dwExitCode:dword

 .data      ;// write your data in this section
    intarray DWORD ?,?,?,?,?,?,?,?,?,?
     msg2 BYTE "The processed array:", 0
     endl BYTE 0dh, 0ah, 0
     count DWORD 0
     x DWORD 0
     y DWORD 0


 .code      
    main proc
    mov eax, 0 ; zeros out the eax register
    mov ecx, LENGTHOF intarray 
    mov edi, OFFSET intarray; 
    mov edx, OFFSET endl; moves the location of endl to edx

 L1:
     call ReadInt ; takes user integer input for the eax register
     mov [edi], eax; moves value from the eax register to the edi
     add edi, TYPE DWORD; increments the address 
     Loop L1; restarts first loop


     mov edx, OFFSET msg2 ; moves msg2 to the edx register
     call WriteString ; Writes the value in the edx register to the screen
     mov edx, OFFSET endl ; moves endl (line break) to the edx register
     call WriteString ; prints the value in the edx register to the screen


    mov ecx, LENGTHOF intarray/2 ;
      L3: 

     Loop L3 ; restarts the loop

     mov ecx, LENGTHOF intarray ;
     mov edi, OFFSET intarray; 

      L4:
          mov eax, edi;
          call WriteInt 
          add edi, TYPE DWORD; increments the address 

      loop L4

     invoke ExitProcess,0
 main endp
 end main

Solution

  • Read both array elements in registers, then perform the add or sub at the requested end of the array.
    Advance the pointer in EDI but lower ECX twice as fast.

        mov edi, OFFSET intarray
        mov ecx, 9            ;10 elements in the array
    Again:
        mov eax, [edi]
        mov ebx, [edi+ecx*4]
        add [edi], ebx
        sub [edi+ecx*4], eax
        add edi, 4
        sub ecx, 2
        jnb Again