我在NASM中遇到阵列问题。我正在尝试实现此伪代码,但结果不正确。
例如,当我发送' abcdefgh' as byte_arr我应该得到8 7 6 5 4 3 2 1.然而,我实际收到:5 4 3 2 1 1 1 1.这里是代码:
maxLyn(Z[0 . . n − 1], n, k) : returns integer
if k = n − 1
return 1
p ← 1
for i ← k+1 to n − 1
{
if Z[i−p] = Z[i]
if Z[i−p] > Z[i]
return p
else
p ← i+1−k
}
return p.
我希望将它存储为全局变量,而不是返回p,我可以在其他子例程中访问它。以下是我编写代码的尝试:
enter 0, 0 ; creates stack
pusha ; pushes current register values onto stack
mov eax, [ebp+16] ; kth index
mov ebx, [ebp+12] ; length
mov edi, [ebp+8] ; byte_arr
mov [len], ebx ; len = length
sub [len], dword 1 ; len = len - 1
mov ebx, [len] ; ebx contains len - 1
mov [k], eax ; k = epb+16
mov [p], dword 1 ; p = 1
mov [i], eax ; i = k
inc dword [i] ; i = k+1
mov ecx, [i] ; ecx = i
cmp [k], ebx ; checks if kth index is last element
je ENDFOR
FOR: cmp dword [i], ebx ; goes from ith index to len
ja ENDFOR
mov esi, [edi + ecx*1] ; esi = array[i]
mov [i_temp], esi ; store array[i] in variable
sub ecx, [p] ; ecx = i-p
mov edx, [edi + ecx*1] ; edx = array [i-p]
cmp edx, [i_temp]
je REPEAT ; array[i-p] = array[i]
ja ENDFOR ; array[i-p] > array[i]
mov eax, dword [i]
mov [p], eax ;p = i
inc dword [p] ;p = i + 1
mov eax, dword [p]
sub eax, [k] ;eax = p - k
mov [p], eax ;p = i+1-k
REPEAT:
inc dword [i] ; i = i + 1
mov ecx, [i] ; ecx = i + 1
jmp FOR
ENDFOR:
popa ; saves register values and pops them off
leave ; cleans up
ret ; returns to caller
答案 0 :(得分:2)
mov esi, [edi + ecx*1] ; esi = array[i]
mov [i_temp], esi ; store array[i] in variable
sub ecx, [p] ; ecx = i-p
mov edx, [edi + ecx*1] ; edx = array [i-p]
cmp edx, [i_temp]
je REPEAT ; array[i-p] = array[i]
ja ENDFOR ; array[i-p] > array[i]
在这些行中,您将数组元素读为 dwords ,但实际上您使用的是字节数组!
这就是比较失败的原因。将此cmp
更改为:
cmp dl, byte ptr [i_temp]
或者重新编写代码,以便在适当的地方使用字节大小的变量/寄存器。