Copying Array Content to Another Array in Assembly

10,513

Solution 1

You can't do direct memory-to-memory moves in x86. You need to use another scratch register:

mov ecx, [edx]
mov [eax], ecx

Or something like that...

Solution 2

Both ia32 and ia64 do contain a memory-to-memory string move instruction that can move bytes, "words", and "doublewords".

movsb
movsw
movsd

The source address is specified in ESI and the destination in EDI.1 By itself, it moves one byte, word, or doubleword. If the rep prefix is used, then ECX will contain a count and the instruction will move an entire string of values.


1. I think these instructions are the reason that the ESI and EDI registers are so named. (Source Index and Destination Index.)

Share:
10,513
Gavin
Author by

Gavin

Updated on June 05, 2022

Comments

  • Gavin
    Gavin almost 2 years

    I'm looking to copy some elements of an array to another one in Assembly. Both arrays are accessed via pointers which are stored in registers. So, edx would be pointing to one array and eax would point to another. Basically, edx points to an array of character read in from a text file, and I'd like eax to contain only 32 of the characters. Here's what I'm attempting to do:

    I386 Assembly using NASM

    add edx, 8 ; the first 8 characters of the string are not wanted
    
    mov cl, 32
    ip_address:
    ; move the character currently pointed to by edx to eax (mov [eax], [edx])
    inc edx
    inc eax
    loop ip_address
    

    Again, i'd like this to place the 32 characters after the first eight to be placed in the second array. The problem is that I'm stumped on how to do this.. Any help is very much appreciated.

  • Stephen Canon
    Stephen Canon about 13 years
    You get a segfault when you use ecx because it overwrites your loop counter (cl is the low 8 bits of ecx). You need to use a different register for the copy: ebx seems the logical choice.
  • Gavin
    Gavin about 13 years
    @Stephen Canon Actually, I was using ebx. The seg fault was due to mov cl, 32 being commented out.
  • Gavin
    Gavin about 13 years
    Thanks, Stephen. I'll have to remember that if I ever need an alternative to the above.
  • ninjalj
    ninjalj about 13 years
    Or you could use rep movs to copy from [esi] to [edi].
  • DigitalRoss
    DigitalRoss about 13 years
    Actually, you can do "direct memory-to-memory moves in x86".
  • Stephen Canon
    Stephen Canon about 13 years
    @ninjalj: you could, but calling memcpy will be substantially faster on at least some architectures.
  • The Mask
    The Mask about 11 years
    @DigitalRoss: You mean in a modern intel processor? and How?
  • Carl Norum
    Carl Norum about 11 years
    @TheMask, he's referring to the string copy instructions. See his answer.