Friday, 22 February 2019

Assembly: Reverse a string using a loop

Increments an index to visit each character in a string. Once the length of the string has been determined, decrements the index again to display the characters in reverse order.


program reverse_string;
#include( "stdlib.hhf" )
static
    zeroTerminatedString: char; @nostorage;
    byte "There and back again", 0;

begin reverse_string;
    mov( &zeroTerminatedString, ebx );
    stdout.put( nl );
    stdout.put( "Base address where string begins is held in register ebx = " );
    stdout.put( ebx );
    stdout.put( nl, nl );

    mov( 0, eax );
    visitCharacter:
        mov( ebx, ecx );
        add( eax, ecx );

        cmp( (type byte [ecx]), 0 );
        jz outputLength;

        stdout.put( "Index address eax = " );
        stdout.put( eax );
        stdout.put( stdio.tab );

        stdout.put( "Mem address ebx+eax = " );
        stdout.put( ecx );
        stdout.put( stdio.tab );

        stdout.put( "Contents = " );
        stdout.put( ( type byte [ecx] ) );
        stdout.put( stdio.tab );

        stdout.put( "ASCII char = " );
        stdout.put( ( type char [ecx] ) );
        stdout.put( nl );


        inc( eax );

        jmp visitCharacter;
    outputLength:
        stdout.put( nl );
        stdout.put( "Length of string held in register eax = " );
        stdout.put( ( type uns32 eax ) );
        stdout.put( nl, nl );

    reverseString:
        dec( eax );
    revisitCharacter:
        mov( ebx, ecx );
        add( eax, ecx );

        stdout.put( "Index address eax = " );
        stdout.put( eax );
        stdout.put( stdio.tab );

        stdout.put( "Mem address ebx+eax = " );
        stdout.put( ecx );
        stdout.put( stdio.tab );

        stdout.put( "Contents = " );
        stdout.put( ( type byte [ecx] ) );
        stdout.put( stdio.tab );

        stdout.put( "ASCII char = " );
        stdout.put( ( type char [ecx] ) );
        stdout.put( nl );

        dec( eax );
        jge revisitCharacter;
 
end reverse_string;