Friday, 22 February 2019

Assembly: Determine length of a string

Ssshh! It's a DELIBERATELY ANNOYING LOW-LEVEL PROGRAM
This is not the sort of thing that people should EVER mess about with.

EVER.

Apparently.

Because it's written in HLA assembly language for an Intel processor.

Schools and colleges in the UK don't like assembly language. It's official.


So here's the code:
program determine_string_length;

#include( "stdlib.hhf" )

static
    zeroTerminatedString:   char;    @nostorage;
    byte    "Hello from RAM", 0;

begin determine_string_length;
        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 held in register eax = " );

        stdout.put( ( type uns32 eax ) );
        stdout.put( nl );

end determine_string_length;