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
    ld a,(hl)
    or a
    ret z
    call putchar
    inc hl
    jr putstr

    ld hl,#MsgHelloWorld
    call putstr

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

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

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

;subroutine to print inline strings
    ;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
    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
;restore the stack pointer which point to the code after the string
    ex sp,hl


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: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s