assembly - 开始组装,简单的计算器问题

标签 assembly x86 user-input

我想说,我在汇编方面完全是菜鸟,几天前才开始学习。了解了一些有关用户输入、寄存器和定义的知识。现在我尝试将所有这些结合到一个计算器程序中。但一开始总结,有一个问题。程序输出欢迎消息,但不打印结果。
有人可以帮我吗?


section .bss
sinput1: resb 255
sinput2: resb 255<p></p>

<p>section .data
msg db 'Welcome to the Calculator',0xa
lenMsg equ $ - msg</p>

<p>section .text
global _start</p>

<p>_start:
;Print out the Welcome message
mov eax,4
mov ebx,1
mov edx, lenMsg
mov ecx, msg
int 80h
;Input first digit
mov edx,255
mov ecx,sinput1
mov ebx,0
mov eax,3
int 80h
;Input second digit
mov edx,255
mov ecx,sinput2
mov ebx,0
mov eax,3
int 80h
;Sum them up
mov esi,sinput1
mov edx,sinput2
add esi,edx
;Print out the result
mov eax,4
mov ebx,1
mov edx, 255
mov ecx, esi
int 80h
;Quit the program
mov eax,1
int 80h
</p>

最佳答案

指令mov esi, sinput1将第一个缓冲区的地址移动到ESI寄存器中,但您确实想要存储在那里的字节。您可以通过 mov al, [sinput1] 检索它。
类似地,指令 mov edx, sinput2 将第二个缓冲区的地址移动到 EDX 寄存器中,但您确实想要存储在那里的字节。您可以通过 mov dl, [sinput2] 检索它。

接下来这些字节将是字符,希望在“0”到“9”范围内,但是您的添加希望能够使用这些字符代表的值。为此,您需要从两个字符的 ASCII 代码中减去 48。

一旦获得正确的总和,您需要将其转换为字符以准备显示。这需要您添加 48 以获得 sys_write 可以使用的 ASCII 代码。

下面的代码将输出

Welcome to the Calculator
7

如果您使用以下键输入

3输入4输入

mov al, [sinput1]   ; Character "3"
sub al, '0'         ; Convert to 3
mov dl, [sinput2]   ; Character "4"
sub dl, '0'         ; Convert to 4
add al, dl          ; Sum is 7
add al, '0'         ; Convert to character "7"
mov ah, 0Ah         ; Newline
mov [sinput1], ax   ; Store both in buffer

;Print out the result
mov edx, 2          ; Character and Newline
mov ecx, sinput1    ; Buffer
mov ebx, 1          ; Stdout
mov eax, 4          ; sys_write
int 80h

要使其成为一个强大的程序,您仍然需要

  • 检查两个输入的有效性
    • 是否输入过任何内容?从sys_read检查EAX!
    • 输入是否代表数字?
    • 这个数字在允许的范围内吗?
  • 为总和大于9时做准备(需要多于1个输出字符)。

关于assembly - 开始组装,简单的计算器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54598515/

相关文章:

assembly - MOV moffs32 在 64 位模式下对地址进行符号或零扩展?

performance - 此次主机扫描中最快的 SSL 加密算法是什么?

c - 如何用C软件中断正在运行的函数?

Shell脚本读取文件路径直到文件存在

assembly - 如何使用汇编写入标准输出?

macos - 这种 x86 调用约定的原因是什么?

c++ - 与裸 __m128 相比,SSE vector 包装器类型的性能

performance - 为什么循环总是编译成 “do…while”样式(尾跳)?

java - Java 可以识别用户输入中的变量吗?

java - 从字符串输入构建树