2012-10-13 29 views
2

我一直在閱讀「從頭開始編程」一書,在Linux中學習彙編編程。我在第三章末尾解決了其中一個練習時遇到了問題。 練習說修改下面的程序,使用數據集末尾的地址來終止循環。這只是一個簡單的程序,用於查找一組數據中的最大數量,它目前僅使用數字零來標記數據的結尾。獲取一組數據末尾的地址?

#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: 
    .long 3, 67, 34, 14, 45, 75, 54, 187, 44, 87, 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      # The biggest 

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 the beginning if new value 
             # Isn't larger 
movl %eax, %ebx      # Move the value as the largest 
jmp  start_loop      # Jump to the beginning of loop 

loop_exit: 

# %ebx is the status code for the exit system call 
# and it contains the maximum number 
movl $1, %eax       # 1 is the exit() system call 
int  $0x80 

我知道,我可能只是硬編碼數據的列表的長度,我也可以將其存儲在數據的第一個字節,但鍛鍊是要求使用的地址,以終止循環最後的元素。這本書提到使用符號來標記結尾。我認爲我的問題是我不明白如何獲得地址。如果我知道如何得到它,我可以把它存儲在一個寄存器中。任何幫助表示讚賞。

回答

0

問問自己:我知道數據的起始地址嗎?我怎麼知道它?我知道數據的大小嗎?我怎麼知道這個?我能從這些信息中瞭解結束地址嗎?

+0

這是我遇到的麻煩是最後一個問題。 –

+0

如果您知道起始地址,數據中的項目數量以及您靈魂能夠計算結束地址的每個元素的大小,如果你知道如何聲明標籤,你可以更容易,也許你可以在最後一個元素附近聲明一個標籤? –

2

隨着Mac OSX上一些微小的器官功能障礙綜合徵...

.data 

data_items: 
    .long 3, 67, 34, 14, 45, 75, 54, 187, 44, 87, 22, 11, 66, 0 
data_end: 

.text 

.globl start 
start: 
     movl $0, %edi      # Move 0 into the index register 
     movl data_items (, %edi, 4), %eax # Load the first data value 
     movl %eax, %ebx      # The biggest 
     leal data_end, %ecx     # Load and save ending address 

start_loop: 
     leal data_items(, %edi, 4), %eax # Get address of next value 
     cmpl %eax, %ecx      # Check to see if we've hit the end 
     je  loop_exit 
     incl %edi       # Increment index 
     movl (%eax), %eax     # Load value 
     cmpl %ebx, %eax      # Compare values 
     jle  start_loop      # Jump to the beginning if new value 
               # Isn't larger 
     movl %eax, %ebx      # Move the value as the largest 
     jmp  start_loop      # Jump to the beginning of loop 

loop_exit: 
     movl $1, %eax      # 1 is the exit() system call 
     pushl %ebx 
     pushl $0 

     int  $0x80