Copy a string: Difference between revisions
Content added Content deleted
Puppydrum64 (talk | contribs) |
Puppydrum64 (talk | contribs) |
||
Line 63: | Line 63: | ||
Terminated: ;the null terminator is already stored along with the string itself, so we are done. |
Terminated: ;the null terminator is already stored along with the string itself, so we are done. |
||
;program ends here.</lang> |
;program ends here.</lang> |
||
=={{header|8086 Assembly}}== |
|||
The technique varies depending on whether you just want a new reference to the old string or to actually duplicate it in RAM. Strangely, this is one of the few things that's actually easier to do correctly in assembly than in high-level languages - it's very unlikely you'll do the wrong one by accident. |
|||
===Making a new reference=== |
|||
This technique is useful if you wish to create a struct/record that needs to be able to retrieve a string quickly. All you need to do is get a pointer to the desired string and store it in RAM. |
|||
<lang asm>.model small |
|||
.stack 1024 |
|||
.data |
|||
myString byte "Hello World!",0 ; a null-terminated string |
|||
myStruct word 0 |
|||
.code |
|||
mov ax,@data |
|||
mov ds,ax ;load data segment into DS |
|||
mov bx,offset myString ;get the pointer to myString |
|||
mov word ptr [ds:myStruct],bx |
|||
mov ax,4C00h |
|||
int 21h ;quit program and return to DOS</lang> |
|||
===Creating a "deep copy"=== |
|||
This method will actually make a byte-for-byte copy somewhere else in RAM. |
|||
<lang asm>.model small |
|||
.stack 1024 |
|||
.data |
|||
myString byte "Hello World!",0 ; a null-terminated string |
|||
StringRam byte 256 dup (0) ;256 null bytes |
|||
.code |
|||
mov ax,@data |
|||
mov ds,ax ;load data segment into DS |
|||
mov es,ax ;also load it into ES |
|||
mov si,offset myString |
|||
mov di,offset StringRam |
|||
mov cx,12 ;length of myString |
|||
cld ;make MOVSB auto-increment rather than auto-decrement (I'm pretty sure DOS begins with |
|||
;the direction flag cleared but just to be safe) |
|||
rep movsb ;copies 12 bytes from [ds:si] to [es:di] |
|||
mov al,0 ;create a null terminator |
|||
stosb ;store at the end. (It's already there since we initialized StringRam to zeroes, but you may need to do this depending |
|||
;on what was previously stored in StringRam, if you've copied a string there already. |
|||
mov ax,4C00h |
|||
int 21h ;quit program and return to DOS</lang> |
|||
=={{header|AArch64 Assembly}}== |
=={{header|AArch64 Assembly}}== |