Skip to content
Advertisement

How to print a number in ARM assembly?

I am trying to print a number that I have stored. I’m not sure if I am close or way off. Any help would be appreciated though. Here is my code:

.data
.balign 4
a: .word 4

.text
.global main
main:
        ldr r0, addr_of_a
        mov r1, #8
        str r1, [r0]
write:
        mov r0, #1
        ldr r1, addr_of_a
        mov r2, #4
        mov r7, #4
        swi #0
        bx lr

addr_of_a: .word a

It compiles and runs, but I don’t see anything printed. From what I understand, I need the address of where to start printing in r1, how many bytes in r2, the file descriptor in r0, and r7 specifies the write call if it is set to #4. I am simply trying to store #8, then print the stored number.

Advertisement

Answer

The syscall write takes on the second argument (r1) as a pointer to the string you want to print. You are passing it a pointer to an integer, which is why it’s not printing anything, because there are no ASCII characters on the memory region you are passing to it.

Below you’ll find a “Hello World” program using the syscall write.

.text
.global main
main:
        push {r7, lr}

        mov r0, #1
        ldr r1, =string
        mov r2, #12
        mov r7, #4
        svc #0

        pop {r7, pc}

.data
string: .asciz "Hello Worldn"

If you want to print a number you can use the printf function from the C library. Like this:

.text
.global main
.extern printf
main:
        push {ip, lr}

        ldr r0, =string
        mov r1, #1024
        bl printf

        pop {ip, pc}

.data
string: .asciz "The number is: %dn"

Finally, if you want to print the number with the syscall write you can also implement a itoa function (one that converts an integer to a string).

Advertisement