【发布时间】:2018-02-01 14:15:10
【问题描述】:
我有一个小型汇编程序,我试图读取一个整数并验证它是否在 [0-100,000] 之间。这目前不起作用。此时,一个有效的整数(例如 10)将导致程序跳转到invalidInput 标签,然后程序退出。
我认为这个错误的原因是由于跳转之前的比较。是否有不同的方式来比较用户输入的整数?
我认为读入的值必须更改为整数(从“字符串”转换?)
这是我的第一个汇编程序之一,所以我还在学习基础知识。
section .bss
value: resb 4
section .data
prompt db 'Enter a integer between [0-100000]: ', 0xa
promptLen equ $-prompt
invalidMsg db 'Invalid data. Integers between [0-100000] are valid. Exiting.', 0xa
invalidMsgLen equ $-invalidMsg
section .text
global _start
_start:
; Display prompt
mov rdx, promptLen ; message length
mov rcx, prompt ; message to write
mov rbx, 1 ; file descriptor for stdout
mov rax, 4 ; system call for sys_write
int 0x80 ; call kernel
;Read the value and store it
mov rax, 3 ; sys_read
mov rbx, 0 ; descriptor value for stdin
mov rcx, value ; where to store the input
mov rdx, 5 ; 5 bytes
int 80h ; call kernel
mov edx, value ; move value to a register before comparing
cmp edx, 100000
jg invalidInput ; jump if the input is greater than 100000
cmp edx, 0
jl invalidInput ; jump if the input is less than 0
; Other instructions (that aren't important for now) here
invalidInput:
mov rdx, invalidMsgLen ; message length
mov rcx, invalidMsg ; message to write
mov rbx, 1 ; file descriptor for stdout
mov rax, 4 ; system call for sys_write
int 0x80 ; call kernel
mov rax, 1 ; exit
int 0x80
如何验证此输入?
【问题讨论】:
-
sys_read得到的是字符串。所以,是的,如果你想将它与整数进行比较,你必须编写一个将字符串转换为整数的函数。您应该能够在 StackOverflow 和其他地方找到大量关于如何做到这一点的示例。