在我们大学的时候,老师都会让我们用C 语言、JAVA语言输出打印一些图形,这篇文章我们就来讨论一下怎么用AT&T汇编打印一个三角形。
我们先来看一下三角形,假设我们要打印6行,我们可以发现,第一行前面要打印的空格数比行数少1,也就是5行,然后每一行要打印的空格数比前一行少1个。第一行要打印一个×号,每行多2个,也就是行数乘以2再减去1。最后每行的×号打印完之后再打印一个换行符。
好了,我们可以试着编一下代码:
#print_triangle.s
#we want to print n line triangle(n should be odd)
#The first line we should print (n-1) space and one *
#
.section .data
space:
.string " "
len=.-space
star:
.string "*"
new_line:
.string "\n"
.section .text
.globl _start
_start:
movl $1, %edi #the current lines
movl $6, %esi #the total lines
out_loop: #control the lines
cmp %esi, %edi
ja exit #if the current lines larger than the control lines then #jump
pushl %edi
control_print_space:
addl $1,%edi #control the number of space
cmp %esi, %edi
ja control_print_star
call print_space
jmp control_print_space
control_print_star:
popl %edi
pushl %edi #Retrieve data in stack
pushl %esi
movl %edi, %eax #calculate the number of star
movl $2, %ebx
mull %ebx
decl %eax
movl %eax, %esi #store the number of star
movl $1, %edi #store the current print number of star
loop_star:
cmp %esi, %edi
ja tidy_stack
call print_star
incl %edi
jmp loop_star
print_space:
movl $space, %ecx #second parameter
movl $len, %edx #third parameter
movl $1, %ebx #first parameter
movl $4, %eax #System call "sys_write"
int $0x80 #soft interrupt call
ret
print_star:
movl $star, %ecx
movl $len, %edx
movl $1, %ebx
movl $4, %eax
int $0x80
ret
tidy_stack:
popl %esi
popl %edi
incl %edi
#print "\n"
movl $new_line, %ecx
movl $len, %edx
movl $1, %ebx
movl $4, %eax
int $0x80
call out_loop
exit:
movl $0, %ebx
movl $1, %eax #System call "sys_exit"
int $0x80
.end
代码看起来有些繁琐,但不影响我们阅读,我把要打印的分开来,避免代码过长。ok,我们编译运行一下
as --32 -o print_triangle.o print_triangle.s
ld -m elf_i386 -o print_triangle print_triangle.o
好了,成功了。文章到这里也该结束了,希望这篇文章可以帮到大家,有什么不懂的地方欢迎大家在下方评论,我们相互学习,感谢大家观看。