【程序员必备小知识-汇编知识25】初识汇编

226 阅读2分钟

引言

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动

我们今天继续来聊汇编,昨天我们学习了一些通用寄存器,下面我们来用一段汇编代码来了解一下这些寄存器是怎么工作的?

求最大值

#PURPOSE: This program finds the maximum number of a
#	  set of data items.
#这个程序是求最大值的程序
#VARIABLES: The registers have the following uses:
#
# %edi - Holds the index of the data item being examined
# %ebx - Largest data item found
# %eax - Current data item
#
# The following memory locations are used:
#
# data_items - contains the item data. A 0 is used
# to terminate the data
#
 .section .data
data_items: 		#These are the data items
 .long 3,67,34,222,45,75,54,34,44,33,22,11,66,0

 .section .text
 .globl _start
_start:
 movl $0, %edi  	# move 0 into the index register
 movl data_items(,%edi,4), %eax # load the first byte of data
 movl %eax, %ebx 	# since this is the first item, %eax is
			# the biggest

start_loop: 		# start loop
 cmpl $0, %eax  	# check to see if we've hit the end
 je loop_exit
 incl %edi 		# load next value
 movl data_items(,%edi,4), %eax
 cmpl %ebx, %eax 	# compare values
 jle start_loop 	# jump to loop beginning if the new
 			# one isn't bigger
 movl %eax, %ebx 	# move the value as the largest
 jmp start_loop 	# jump to loop beginning

loop_exit:
 # %ebx is the status code for the _exit system call
 # and it already has the maximum number
 movl $1, %eax  	#1 is the _exit() syscall
 int $0x80

我们不用会写汇编,但要能看懂,来看看我们的目标是什么:This program finds the maximum number of a set of data items.最大值,在哪里求呢?看到了在data items这里。

那它意味着:.long 3,67,34,222,45,75,54,34,44,33,22,11,66,0,好吧,后面是一堆数,那重点在.long这里,它代表:声明一组数,long类型的,类似于我们java里的数组,那data items自然就相当于数组名了,我们要体会汇编的思想,实际上它并不等同于一个数组名,确切的说更像一个标号,有了这个标号,汇编器就会把这个数组的首地址确定为这个标号所代表的位置。

那除了long类型,自然还有其它数据类型的声明,比如每个数占8位的byte,我们当然也可以用.byte作为一个数组,当然还有很多,这里就不多提了。

接着,我们看我们提到的通用寄存器,毕竟它们才是文章的主角:

  • edi寄存器保存数组中的当前位置,每次比较完一个数就把edi的值加1,指向数组中的下一个数,有点类似于数组中的索引
  • ebx寄存器保存到目前为止找到的最大值,如果发现有更大的数就更新ebx的值,这就是我们定义的max变量。
  • eax寄存器保存当前要比较的数,每次更新edi之后,就把下一个数读到eax中,有点类似于数组中的每个元素

程序的流程就很清楚了,有兴趣的小伙伴可以自行梳理一下,这里就结束了。