【问题标题】:Generic MASM code: storing 8 or 16 bits of a register depending on TYPE of a symbol通用 MASM 代码:根据符号的类型存储 8 位或 16 位寄存器
【发布时间】: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], dlmov [mem], dx 之间进行选择。选择数组的TYPE 仅在它是静态的(而不是函数arg)时才有效,对吧? AFAIK,您不能告诉 MASM 您希望 [esi] 暗示特定的操作数大小。但我不使用 MASM,只使用 NASM/YASM 和 GNU as。

标签: arrays assembly x86 masm


【解决方案1】:

您可以根据 myArray 的类型有条件地将符号定义为文本 dldxedx,并使用它来代替寄存器。比如:

    IF TYPE myArray EQ TYPE BYTE
@DX TEXTEQU <dl>
    ELSEIF TYPE myArray EQ TYPE WORD
@DX TEXTEQU <dx>
    ELSEIF TYPE myArray EQ TYPE DWORD
@DX TEXTEQU <edx>
    ENDIF

    mov @DX, [myArray + eax]   ;puts the left element of the array in DX
    xchg @DX, [myArray + esi]  ;exchange DX with the right element of the array
    mov [myArray + eax], @DX   ;puts the right element into the left part of the array

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-14
    • 2021-07-21
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2011-01-15
    相关资源
    最近更新 更多