Home > Blockchain >  Inserting a character into a string in NASM
Inserting a character into a string in NASM

Time:12-14

I'm trying to do a very simple assembly exercise with NASM, but the everything I've been taught suggests this should work, yet it doesn't.

It's supposed to iterate through the string "Burning The Midnight Oil," and place the characters into dest in reverse, so that it prints "liO thgindiM ehT gninruB" to the output. It does not. It just prints the string of x's, no matter what I do to change it.

What am I missing here? How can I edit the contents of dest after I create it? I am so tired.

global _start
section .text
_start: mov rax, 1
        mov rdi, 1
        mov rsi, dest
        mov rdx, len
        syscall
        mov rax, 60
        xor rdi, rdi
        syscall
section .data
src:    db 'Burning The Midnight Oil', 10
dest:   db 'xxxxxxxxxxxxxxxxxxxxxxxx', 10
len:    equ $ - dest

        xor rcx,rcx
        mov rcx,len
        mov rsi,len
loopstart:
        sub rsi,rcx
        mov al,[src rcx]
        mov [dest rsi],al
        dec rcx
        jnz loopstart

CodePudding user response:

The program starts executing at the _start label. You immediately display and exit even before processing the string! Move the loop code at _start:.

Your len: equ $ - dest includes the newline code (10). That's wrong! You must leave that byte where it is.

len:    equ ($ - dest) - 1   ; Iteration count

Writing to the last position of the string requires using "Length - 1", therefore write mov [dest rsi-1], al

Copying the string just requires using two offsets: one incrementing and the other decrementing until zero:

_start:
    mov  rdi, len
    xor  esi, esi
loopstart:
    mov  al, [src   rsi]
    mov  [dest   rdi - 1], al
    dec  rdi
    jnz  loopstart

    mov rax, 1
    mov rdi, 1
    mov rsi, dest
    mov rdx, len
    syscall
    mov rax, 60
    xor edi, edi
    syscall
  • Related