Reputation: 11
I need to swap two arrays where:
array1 = [10,9,8,7,6]
array2 = [5,4,3,2,1]
This is my assembler code:
.data
array1 DWORD 1, 2, 3, 4, 5
array2 DWORD 6, 7, 8, 9, 10
.code
main proc
mov eax,array2+16
mov edx,array1
mov array1,eax
mov array2+16,edx
mov eax,array2+12
mov edx,array1+4
mov array1+4,eax
mov array2+12,edx
mov eax,array2+8
mov edx,array1+8
mov array1+8,eax
mov array2+8,edx
mov eax,array2+4
mov edx,array1+12
mov array1+12,eax
mov array2+4,edx
mov eax,array2
mov edx,array1+16
mov array1+16,eax
mov array2,edx
After I did all of this, I looked at my assignment instructions and apparently
0 Is the ONLY immediate/literal value that should be used in instructions.
I also can only use thesub
andmov
instructions.
I just need to know if I need to change anything.
Upvotes: 1
Views: 1926
Reputation: 39516
The constraints for this task are:
sub
and mov
are the only instructions that can be usedBecause the arrays follow each other in memory, I'll take 2 pointers that start at the second array.
array1 DWORD 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
^ ^
| |
array1 array2 = ESI = EDI
The pointer that addresses the first array will pre-decrement and the pointer that addresses the second array will post-increment.
For decrementing, which is subtracting 1, I'll load the first value of the first array which happens to be 1. How convenient!
For incrementing, which is adding 1 but also subtracting -1, I'll subtract that same 1 from the immediate 0 that I'm allowed to use.
Because the arrays hold dwords, it's enough to repeat the decrements/increments 4 times.
The swapping itself is done similar to what you did in your program.
; Setup
mov ecx, array1 ; ECX=1
mov edx, 0
sub edx, ecx ; EDX=-1
mov esi, offset array2
mov edi, offset array2
; Swap array1[4] with array2[0]
sub esi, ecx ; Pre-decrement on ESI (first array)
sub esi, ecx ; Pre-decrement on ESI (first array)
sub esi, ecx ; Pre-decrement on ESI (first array)
sub esi, ecx ; Pre-decrement on ESI (first array)
mov eax, [esi]
mov ebx, [edi]
mov [edi], eax
mov [esi], ebx
sub edi, edx ; Post-increment on EDI (second array)
sub edi, edx ; Post-increment on EDI (second array)
sub edi, edx ; Post-increment on EDI (second array)
sub edi, edx ; Post-increment on EDI (second array)
; Swap array1[3] with array2[1]
...
Because of the severe constraints it's not possible to construct a loop. You'll have to rewrite that last block of code 5 times.
With a few lines of additional setup it's possible to assign ECX=4
and EDX=-4
. That way the pre-decrements and post-increments become but a single instruction each. This will shave off some 25 instructions.
Try for yourself before looking at below snippet!
sub ecx, edx ; ECX=2
sub ecx, edx ; ECX=3
sub ecx, edx ; ECX=4
mov edx, 0
sub edx, ecx ; EDX=-4
Upvotes: 1