【发布时间】:2016-10-12 17:44:19
【问题描述】:
我正在尝试编写一个数组反转函数,无论静态数组是 BYTEs 还是 WORDs,它都能正常工作。
这是我目前所拥有的,我假设数组的大小为WORD
.data
myArray WORD 1231h, 2342h, 3353h, 4564h, 5675h, 7, 9
.code
main proc
mov eax, 0 ;index of the left side of the array
mov esi, SIZEOF myArray
sub esi, TYPE myArray ;index of the right side of the array
Switch:
movsx edx, [myArray + eax] ;puts the left element of the array in eax
xchg dx, [myArray + esi] ;exchange edx with the right element of the array
mov [myArray + eax], dx ;puts the right element into the left part of the array
add eax, TYPE myArray ;eax is currently pointing to leftPtr so we add the appropriate amount to
;it depending on the size of each element in myArray. This way it will point
;to the next element in the array
sub esi, TYPE myArray ;same concept as above except we are subtracting the amount from the right pointer
cmp esi, eax ;compare the right pointer to the left pointer
jnle Switch ;Jump if the right pointer is !(<=) the left pointer
main endp
end main
我可以使用movzx/movsx 指令将较小的值从数组中移动到 32 位寄存器中。
问题是根据TYPE 编写组装到 8 位存储或 16 位存储的内容。
【问题讨论】:
-
不要将
xchg与内存操作数一起使用,除非您想要隐式lock前缀的效果(原子读取-修改-写入内存访问,以及一个完整的内存屏障)。它比仅使用两个 tmp 寄存器要慢得多。也不要忘记在你的函数末尾ret,除非 MASM 为你添加一个。 -
不过,我不知道这里主要问题的答案。您可能必须使用 MASM 宏在
mov [mem], dl和mov [mem], dx之间进行选择。选择数组的TYPE仅在它是静态的(而不是函数arg)时才有效,对吧? AFAIK,您不能告诉 MASM 您希望[esi]暗示特定的操作数大小。但我不使用 MASM,只使用 NASM/YASM 和 GNU as。