2016-06-12 40 views
4

我正在嘗試編寫一個數組反轉函數,無論靜態數組是否保存爲​​s或WORDs,都可以正常工作。通用MASM代碼:存儲8位或16位的寄存器,具體取決於符號的類型

這是我迄今爲止其中I假定該陣列是大小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位存儲。

+1

不要使用'xchg'與內存操作數,除非你想* *隱含'lock'前綴的效果(原子的讀 - 修改 - 寫內存訪問,和一個完整的內存屏障)。它比只使用兩個tmp寄存器慢得多。除此之外,不要忘記在你的函數結尾處「ret」,除非MASM爲你添加一個。 –

+0

雖然我不知道主要問題的答案。您可能不得不使用MASM宏在'mov [mem],dl'和'mov [mem],dx'之間選擇。選擇數組的'TYPE'只有在靜態時才起作用(而不是函數arg),對吧? AFAIK,你不能告訴MASM你想''esi]'暗示一個特定的操作數大小。但是我不使用MASM,只是NASM/YASM和GNU。 –

回答

4

您可以在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 
相關問題