2013-08-30 40 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 
相关问题