【问题标题】:Use a loop to swap the nth position elements from array1 and array2使用循环交换 array1 和 array2 中的第 n 个位置元素
【发布时间】:2020-04-04 20:20:13
【问题描述】:

我目前正在参加装配课程,并且我有一个作业问题我想确保它是正确的。我的问题是:

给出一个名为 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% 确定这是否正确。任何帮助将不胜感激。

【问题讨论】:

  • 使用调试器查看内存内容。

标签: assembly x86 masm swap irvine32


【解决方案1】:
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

更快!

【讨论】:

  • 感谢您的帮助,非常感谢。这更有意义!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-06
  • 1970-01-01
  • 2017-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多