AArch64 Looping first 50 even numbers.
Hi everyone, I am writing a blog about a practice exercise for assembly language for AArch64. Recently, I was studying about the assembly language commands and registers for both x86_64 and arch64 systems. I completed several labs, which gave me good understanding about the registers and commands for assembler for both systems. Here is the link to them.
I decided to some practice exercises to improve the understanding of registers and to memorize those commands. I decided to make a program which will loop through first 50 numbers and print the even numbers only.
Here is the source code of the program:
.text
.globl _start
min = 0
max = 51 /* loop exits when the index hits this number (loop condition is i<max) */
_start:
mov x19, min
mov x21, 10
loop:
/*Start of loop*/
adr x25, msg /*setting the address of string*/
udiv x20, x19, x21 /*unsigned divide - calculating first digit*/
msub x22, x21, x20, x19 /* calulating reminder - second digit */
cmp x19, x21
b.lt DoubleDigits
add x20, x20, '0'
strb w20, [x25, 0] /*writing first digit*/
DoubleDigits:
add x22, x22, '0'
strb w22, [x25, 1] /*writing second digit*/
mov x0, 1
adr x1, msg
mov x2, len
mov x8, 64
svc 0
/*End of loop*/
add x19, x19, 2
cmp x19, max
b.lt loop
mov x0, 0 /* status -> 0 */
mov x8, 93 /* exit is syscall #93 */
svc 0 /* invoke syscall */
.data
msg: .ascii " #\n"
len= . - msg
In this program, I started by defining some macros for minimum and maximum value of the loop. Then I assigned min value to the register which will work as iterator for the loop. In the beginning of the loop I performed udiv and msub to find the first and second digit of the number(I performed these on iterator register - x19 ) Then I checked if first digit is 0 and skipped printing it. For printing the values I used svc to invoke syscall for print which is value 64. After printing both of the digits I checked that if iterator is less than max value, If it is less then loop should repeat or if value is higher than loop should break.
Then, I successfully compiled the program and it ran perfectly. Here is the output of the program:
Comments
Post a Comment