Printing in Binary Form – ARM Assembly

When programming in assembly there are many occasions where you need to examine the bits at a particular register or memory address. Printf doesn’t offer the option to print in binary form, so you need to create your own function if you want to do that. Here’s one that will do just that.

It prints the 32 bits in the same order as they appear (i.e., most significant bit on the left side). Just make sure to push/pop registers r4 and r5 if they are being used elsewhere in your program.

                push {lr}
                mov r5, r0
                mov r6, #0
                        and r1, r5, #2147483648
                        lsr r1, r1, #31
                        ldr r0, =printf2
                        bl printf
                        lsl r5, r5, #1
                        add r6, r6, #1
                        cmp r6, #32
                        blt start
                ldr r0, =printf3
                bl printf
                pop {lr}
                bx lr

        printf2: .asciz "%d"
        printf3: .asciz "n"

Leave a Reply

Your email address will not be published. Required fields are marked *