如何...索引数组的位置... ESI 作为指针
首先数组的定义很重要,如果它是由连续元素组成的简单平面数组,那么要获取地址EDI指向的特定元素的索引,您可以从涉及的两个指针反向计算它(这需要原始数组起始指针仍在ESI!):
mov eax,edi
sub eax,esi ; eax = (element_pointer - array_pointer)
; divide eax by <size_of_element>
; for example your OP code example suggest
; the array element size is DWORD = 4B
; then the division/4 can be done simply:
; shr eax,2
; for byte arrays there's no need to divide the address
; difference, eax already contains index, as BYTE size = 1B
; for other element sizes, which are *not* power-of-two
; (you can't divide the difference by simply shifting it right)
; it may be more efficient to address them through separate index
; or do the: imul/mul (1/el_size) || idiv/div el_size
; (when there's no way to avoid it)
; after division the eax contains 0, 1, ... index.
如果元素的大小不是平凡的(不是二的幂),或者结构不是平凡的(链表,所以两个指针的差异与元素的索引无关),你可能想要计算索引分别地。仍然要避免每次获取索引的mul element_size 可能值得将两者混合,因此通过指针寻址,并分别计算(对获取无用)索引,这将仅用于您需要索引的事物。
另外,在这个变体中,您可以从 1 索引,但我会避免这种情况,除非它是非程序员的一些人工输出,因为大多数 ASM/C/C++ 程序员自然希望索引从 0 开始(由于我的第一个示例中的指针数学如何工作)。
; stolen from Toommylee2k, then modified to focus on my explanation
xor ebx,ebx ; first index will be 1 (!)
; so I initialized ebx = 1 - 1 = 0, because
; I will increment it at beginning of loop
; for indexing from 0 the ebx should be initialized to -1
loop_start:
; update index first, so you can't miss it when branching later
lea ebx,[ebx+1] ; ebx = ebx+1 without flags modification
; since *here* "ebx" works as "index", contains "1" for first item
; do whatever you want with pointers, like "esi" in your sample code
; ...
; move to next element of array (avoids multiplication)
add esi,size_of_element
; although `imul` on modern CPU will perform quite close to `add`
; so when multiplication is unavoidable, go for it.
; the division on the other hand still costs very likely more
; than having separate register/variable for index counting
; loop till ecx is zero (in much faster way than "loop")
dec ecx
jnz loop_start
; "loop" is very slow due to historic reasons, to improve compatibility
最后的扩展,当元素大小是 [1, 2, 4, 8] 之一时,您可以使用扩展的 x86 寻址模式来处理“0, 1, ...”索引而不是纯指针:
mov ebx,7 ; index "7" = 8th element of array
lea esi,[array_of_words] ; array pointer
; addressing through index, supported directly by CPU for size 2
mov ax,[esi + ebx*2] ; complex x86 addressing allows this
; here ax = 8
...
.data
array_of_words:
dw 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
如果您在循环中大量使用索引,这可能是最佳解决方案。如果您很少需要元素的索引,那么纯指针通常更理想。