2013-08-30 60 views
0

讓我們假設我必須將字符串存儲在.BSS部分中創建的變量中。將字符串從BSS變量複製到程序集中的BSS變量

var1 resw 5 ; this is "abcde" (UNICODE) 
var2 resw 5 ; here I will copy the first one 

我該如何與NASM做這件事? 我想是這樣的:

mov ebx, var2 ; Here we will copy the string 
mov dx, 5 ; Length of the string 
mov esi, dword var1 ; The variable to be copied 
.Copy: 
    lodsw 
    mov [ebx], word ax ; Copy the character into the address from EBX 
    inc ebx ; Increment the EBX register for the next character to copy 
    dec dx ; Decrement DX 
    cmp dx, 0 ; If DX is 0 we reached the end 
    jg .Copy ; Otherwise copy the next one 

所以,第一個問題是,字符串是不可複製的UNICODE但作爲ASCII,我不知道爲什麼。其次,我知道可能有一些不推薦使用某些寄存器。最後,我想知道是否有一些更快的方法來做到這一點(也許有專門爲字符串這種操作創建的說明)。我正在談論8086處理器。

+1

'INC' /'dec' /'cmp'?爲什麼不'rep stos'? –

+0

因爲我不知道它。謝謝 – ali

回答

1

inc ebx ; Increment the EBX register for the next character to copy

字爲2個字節,但你只能向前步進ebx 1個字節。將inc ebx替換爲add ebx,2

1

邁克爾已經回答了顯示代碼的明顯問題。

但也有另一層理解。如何將字符串從一個緩衝區複製到另一個緩衝區並不重要 - 按字節,單詞或雙字。它將始終創建字符串的精確副本。

所以,如何複製字符串是一個優化問題。使用rep movsd是已知最快的方法。

這裏是一個例子:

; ecx contains the length of the string in bytes 
; esi - the address of the source, aligned on dword 
; edi - the address of the destination aligned on dword 
    push ecx 
    shr ecx, 2 
    rep movsd 
    pop ecx 
    and ecx, 3 
    rep movsb 
相關問題