【问题标题】:linux nasm assembly display input plus 1linux nasm汇编显示输入加1
【发布时间】:2012-11-03 05:31:38
【问题描述】:

我正在解决一些简单的练习题,其中一个问题是读入一个数字,然后输出该数字加1。

例如:

Please enter a number: 4
5

现在,有了输入和输出,应该很容易。但我想让我的程序能够处理多个数字。这就是我难过的地方。因为如果给我 999 的输入,我的程序怎么会知道将最后的 9 设为 0,并将 1 加到十列?那么,它怎么知道再加一个数字就变成1000呢?

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

SECTION .data
msg        db "Please enter a number: ",0
msglen     EQU $-msg
sz         EQU 32
NUL        EQU 0
len        EQU 32

SECTION .bss
num        resb len

SECTION .text
GLOBAL _start
_start:

Msg:                             ; display the message
mov        eax, 4
mov        ebx, 1
mov        ecx, msg
mov        edx, msglen 
int        80h              

Read:                            ; read in the number
mov        eax, 3
mov        ebx, 1
mov        ecx, num
mov        edx, len
int        80h


Length:                          ; Find length of string
mov        eax, num
mov        ebx, 0
loop:
cmp        BYTE[eax], NUL
je         Set 
inc        eax
inc        ebx
jmp        loop                               

Set:                             ; set up the registers and variables
mov        ecx, num

Print:                           ; main section - prints out the number plus 1
cmp        BYTE[ecx], NUL
je         Exit 
mov        eax, 4
mov        ebx, 1
mov        edx, 1            ; NOTE- does not yet add 1 to the number
int        80h

inc        ecx
jmp        Print 

Exit:                            ; exits safely
mov        eax, 1
mov        ebx, 0
int        80h  

有人可以告诉我如何解决这个问题吗?我只是无法弄清楚添加部分。我可以打印出多个数字,最多 32 位,但添加只是一个谜。

提前致谢,

莱利

【问题讨论】:

    标签: linux assembly x86 nasm


    【解决方案1】:

    使用 atoi() 将其转换为整数然后 printf() 输出结果如何?有一些关于它的示例代码:

    http://cs.lmu.edu/~ray/notes/nasmexamples/

    至于你的整数加法问题,如果我是你,我会先将问题分解为“加一”。你会注意到你正在遵循这个算法:

    1. 将指针设置为字符串中的最后一个字符。
    2. 将字符加一。如果字符低于 ASCII '9',则返回。
    3. 否则,将指针设置为前一个字符。如果它的编号不是-1,则跳转到2。
    4. 如果我们试图覆盖字符号 -1,请为新字符串分配 n+1 个字节,将旧字符串的内容复制到新字符串中,并将“1”作为第一个字符添加。

    从这一点开始,如果您想添加多于一位的输入,您只需弄清楚发生了什么变化。

    【讨论】:

      猜你喜欢
      • 2011-10-17
      • 1970-01-01
      • 2023-03-27
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多