您可以使用lodsl
(默认将%esi向上移动)和loop
(向下移动%ecx)。我不确定它是否比gcc从c生成的效率更高,这基本上是你的代码,但看起来更漂亮。
我在这里所做的并不是完全回答你的问题 - 而是使用loop
作为内部循环我假设整个数组是连续存储的,然后只有一个循环需要担心。在我的机器上用c编译时,它是连续存储的,但我不确定你应该依赖它。希望我所做的已经足够了解loop
和lodsl
是如何工作的,你可以修改你的代码,只在内部循环中使用它们。
.data
x:
.long 6
y:
.long 5
array:
.long 1,1,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1
.text
.global _start
_start:
# set up for procedure call
push x
push y
push $array
# call and cleanup
call cnt
add $0xc, %esp
# put result in %ebx and finish up
#(echo $? gives value in bash if <256)
mov %eax, %ebx
mov $1, %eax
int $0x80
# %ebx will hold the count of 1s
# %ecx will hold the number of elements to check
# %esi will hold the address of the first element
# Assumes elements are stored contiguously in memory
cnt:
# do progogue
enter $0, $1
# set %ebx to 0
xorl %ebx, %ebx
# grab x and y parameters from stack and
# multiply together to get the number of elements
# in the array
movl 0x10(%ebp), %eax
movl 0xc(%ebp), %ecx
mul %ecx
movl %eax, %ecx
# get address of first element in array
movl 0x8(%ebp), %esi
getel:
# grab the value at the address in %esi and increment %esi
# it is put in %eax
lodsl
# if the value in %eax is 1, increment %ebx
cmpl $1, %eax
jne ne
incl %ebx
ne:
# decrement %ecx and if it is greater than 0, keep going
loop getel
# %ecx is zero so we are done. Put the count in %eax
movl %ebx, %eax
# do epilogue
leave
ret
没有所有评论,它确实更漂亮。
.data
x:
.long 6
y:
.long 5
array:
.long 1,1,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1
.text
.global _start
_start:
push x
push y
push $array
call cnt
add $0xc, %esp
mov %eax, %ebx
mov $1, %eax
int $0x80
cnt:
enter $0, $1
xorl %ebx, %ebx
movl 0x10(%ebp), %eax
movl 0xc(%ebp), %ecx
mul %ecx
movl %eax, %ecx
movl 0x8(%ebp), %esi
getel:
lodsl
cmpl $1, %eax
jne ne
incl %ebx
ne:
loop getel
movl %ebx, %eax
leave
ret
请您详细说明一下吗?是否有可能计数ecx,所以0到w以及如何执行检查,比如如果y 0。那去哪里? 所以我有 mov 12(%ebp),%ecx .L14#如上所述。它完成了所有工作,然后返回到ecx = 0? loop .L14 –
beginner
2014-11-01 23:44:50
不,如我所说,'循环'倒数到零。你不能让它数起来。 – Jester 2014-11-01 23:47:36
请注意,您可以使用'mov w,%edx'和'sub%ecx,%edx'这样的东西来获取'%edx'中从'0'到'w-1'的递增计数器。 – 2014-11-04 03:58:46