我目前正在上一门汇编课程,我有一个作业问题,我想确保它是正确的。我的问题指出:
给出一个名为array1的数组,其值分别为1000h,2000h,3000h,4000h,5000h和另一个名为array2的数组,其值分别为11111h,22222h,33333h,44444h,55555h。使用循环来交换array1和array2中的第n个位置元素。
我写了这段代码:
; 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
我的代码可以编译,但我不能100%确定是否正确。任何帮助将不胜感激。
array1 WORD 1000h, 2000h, 3000h, 4000h, 5000h array2 DWORD 11111h, 22222h, 33333h, 44444h, 55555h
如果您希望成功交换一次,则需要定义两个相同大小的数组。您如何将DWORD存储在WORD大小的位置?
不要根据所获得的示例数字选择数据格式,而应根据程序应达到的目标来进行选择。
xchg edi, esi ; swaps values of array1 (esi) and array2 (edi)
这仅交换指针,而不交换它们引用的数据!
下一个代码会交换2个DWORD大小的元素:
mov eax, [esi]
mov edx, [edi]
mov [esi], edx
mov [edi], eax
作为优化,您应将loop L1
指令替换为
dec ecx
jnz L1
更快!