问题描述
我正在编写一个汇编代码以获取一个数字,并打印一些与该数字相同的文本.
I am writing an assembly code to get a number and print some text as many times as that number.
例如,当输入为4时,我要写"Hello!". 4次.
for example when the input is 4, I want to write "Hello!" 4 times.
我的代码:
section .data
msg db 'Hello!',0xA
len equ $-msg
section .bss
n resb 1
section .text
global _start
_start:
mov edx, 1
mov ecx, n
mov ebx, 0
mov eax, 3
int 0x80
mov ecx, n
loop1:
push ecx
mov edx, len
mov ecx, msg
mov ebx, 1
mov eax, 4
int 0x80
pop ecx
loop loop1
mov eax, 1
int 0x80
我在终端中使用此代码运行它
I run it with this codes in terminal
nasm -f elf32 test.asm
ld -m elf_i386 -o test test.o
./test
但是我得到一个无限的你好!"
But i get an infinity "Hello!"
推荐答案
mov ecx, n
在NASM中,类似这样的指令将变量的地址加载到ECX
中.
(MASM会抱怨该变量不是双字!)
In NASM an instruction like this loads the address of the variable in ECX
.
(MASM would have complained about the variable not being a dword!)
您知道这一点是因为您将其正确地用于输入单个字符.
You knew this since you used it correctly for the input of the single character.
但是,初始化循环计数器的指令应已取消引用以获得实际输入.您需要为此使用方括号.
However the instruction that initializes the loop counter should have dereferenced to obtain the actual input. You need to use square brackets for this.
仅靠现在这还不够!您得到的输入代表一个数字字符,您需要该数字的实际值.
例如如果输入字符"4",则变量 n 将保留52.
Now by itself this is not enough! The input that you got represents a digit character where you need the actual value of that digit.
e.g. If you input the character "4", the variable n will hold 52.
movzx ecx, byte [n] ; Load 1 byte and store in dword register
sub cl, '0' ; Convert from character "4" to value 4 (e.g.)
loop1:
这篇关于NASM:循环变成无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!