reverse.asm

URL: https://mirkwood.cs.edinboro.edu/~bennett/class/cmsc3100/spring2026/notes/functions/code/reverse.asm
 
%include "CONSTANTS.h"

section .data

   endl: db `\n`
   fmtString: db `The string is \"%s\"\n`,0

   phrase: db "Hello world!",0

section .bss
   esarhp: resb 100

section .text

global main
main:
    mov r9, 0
    mov rax, 0

LoadLoop:
    ; load the letter 
    mov al, byte [phrase + r9]

    ; check to see if it is the null terminator
    cmp al, 0
    je .done

    ; push it onto the stack
    push rax

    ; for debugging
    ; the stack might not be alligned, so we can not make a function call
    ; but we can do a syscall
    mov rax, SYS_WRITE
    mov rsi, STDOUT

    mov rsi, phrase 
    add rsi, r9
    mov rdx, 1
    syscall

    ; move to the next letter
    inc r9 
    jmp LoadLoop

.done:

    ; print newline, remember the stack might not be alligned, so we can't
    ; call printf
    mov rax, SYS_WRITE
    mov rsi, STDOUT

    mov rsi, endl 
    mov rdx, 1
    syscall

    ; r8 will point into the reversed string
    mov r8, esarhp

PrintLoop:
   
    ;  count down in r9
    cmp r9, 0
    je .done

    ; get the letter off the stack
    pop rax

    ; save it in the new string
    mov [r8], al

    ; for debugging
    mov rax, SYS_WRITE
    mov rsi, STDOUT

    mov rsi, r8
    mov rdx, 1
    syscall

    inc r8
    dec r9
    jmp PrintLoop

.done:
    ; null terminate the string
    mov byte [r8], 0

    ; we could call printf here, as the stack should be "back"
    mov rax, SYS_WRITE
    mov rsi, STDOUT

    mov rsi, endl 
    mov rdx, 1
    syscall


    ; print the original string
    mov rdi, fmtString
    mov rsi, phrase
    call CallPrintf

    ; print the reversed string
    mov rdi, fmtString
    mov rsi, esarhp
    call CallPrintf

    jmp Exit