Assembler trick: inline strings

Quite often, we need to send strings to a computer. Usually, there is a section in your code where you define the message with a label:

;string is terminated with null
MsgHelloWorld: .asciz "Hello World!\r\n"

;subroutine to print strings
putstr: 
    ld a,(hl)
    or a
    ret z
    call putchar
    inc hl
    jr putstr

main:
    ld hl,#MsgHelloWorld
    call putstr
    halt

With a bit of extra code, we can make some code with embedded strings.

main:
    call   putstr_imm
    .asciz "Hello World\r\n"

    call   putstr_imm
    .asciz "Hello World again\r\n"
    halt

;subroutine to print inline strings
putstr_imm:
    ;this exchange the stack pointer (SP) with HL
    ex sp,hl

    ;at this point, HL points to the code after the call,
    ;but we placed data instead, terminated with a null.
    ;So we skip the data while printing it. 
    ;When done, normal code follows
put1:
    ld a,(hl)
    or a
    jr nz,put_ret ;if null detected we resume code
    call putchar ;else we print bytes
    inc hl
    jr put1
put_ret:
;restore the stack pointer which point to the code after the string
    ex sp,hl
    ret

 

Advertisements
This entry was posted in assembler, Software, Z80 and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s