需要帮助使用MASM汇编程序将伪代码转换为80x86汇编语言程序



我使用的是Visual Studio 2012,在windows32解决方案中编辑.asm文件。

这是需要更改为汇编的伪代码:

Declare a 32-bit integer array A[10] in memory
repeat
Prompt for and input user's array length L
until 0 <= L <= 10
for i := 0 to (L-1)
Prompt for and input A[i]
end for
while (First character of prompted input string for searching = 'Y' or 'y')
Prompt for and input value V to be searched
found := FALSE
for i := 0 to (L-1)
if V = A[i] then
found := TRUE
break
end if
end for
if (found) then
Display message that value was found at position i
else
Display message that value was not found
end if
end while

我可以很好地管理输入、循环和跳跃,但让我感到困惑的是,让数组具有用户输入的长度,并在数组中运行以比较值。最能帮助我的是,如果有人制作并解释一段代码,帮助我理解我没有得到的部分。我试过在网上搜索它,但我遇到的几乎所有东西都使用了不同的汇编程序,这让我很难解析。

到目前为止,我的代码是:

.586
.MODEL FLAT
INCLUDE io.h            ; header file for input/output
.STACK 4096
.DATA
lengthA DWORD   ?
promptL BYTE    "Please enter a length of the array between 0 and 10: ", 0
string  BYTE    40 DUP (?)
A       DWORD   0  DUP (?)
.CODE
_MainProc PROC
Reread: input   promptL, string, 40     ; read ASCII characters
atod    string                  ; convert to integer
;while (promptL < 0 or > 10)
cmp eax, 0
jl  Reread
cmp eax, 10
jg  Reread
;end while
mov     lengthA, eax            ; store in memory
_MainProc ENDP
END                             ; end of source code

在检查用户输入是否在范围内后,我遇到了一堵砖墙,不确定如何将数组a设置为具有指定的长度,甚至不确定我是否正确地声明了a。

您不能在运行时修改汇编时间常数。DUP指令就是汇编时间指令,它通过在生成的机器代码中多次发出"init"值来保留内存空间。这形成了一个固定的可执行文件,该可执行文件仅限于组装过程中使用的大小。

由于您的最大L为10,您可以为最大可能大小保留阵列:

A       DWORD   10  DUP (?)

然后在代码的后面,您必须获取[lengthA]才能知道使用了多少元素(使其看起来像动态调整大小的数组,并且不处理地址A之后保留的剩余未使用部分)。

另一种选择是在运行时动态保留内存,方法是调用操作系统服务来分配堆内存,或者在堆栈上保留数组。但这两种选择都比使用如上所述的固定大小内存要先进得多。

我在您的伪代码中没有看到任何动态内存分配的请求,具有固定大小数组的解决方案对我来说还可以,尤其是如果您已经在努力解决它,那么您可能还没有准备好编程自己的动态内存管理器/分配器。

编辑:事实上,伪代码确实指定你应该保留固定大小的内存,我一开始不知怎么忽略了它:

Declare a 32-bit integer array A[10] in memory

因此,使用[lengthA]:的伪代码示例

; for i := 0 to (L-1)
xor     edi,edi         ; index i
input_loop:
cmp     edi,[lengthA]
jge     input_loop_ends ; if (i >= L), end for
; TODO: Prompt for and input A[i]
; eax = input value, preserve edi (!)
mov     [A + 4*edi],eax ; store value into A[i]
; end for
inc     edi             ; ++i
jmp     input_loop
input_loop_ends:
; memory at address A contains L many DWORD values from user

最新更新