【问题标题】:NASM: Validating inputNASM:验证输入
【发布时间】: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 和其他地方找到大量关于如何做到这一点的示例。

标签: assembly nasm x86-64


【解决方案1】:

你读取的字符串必须转换为二进制值(你已经说过你认为它应该转换为整数,嗯,就是这样一个二进制值),然后你才能将它与另一个数字进行比较。所以找到一个转换例程(网络上有很多例子,在 Stack Overflow 上)。

另外,如果你在 NASM 中写

    mov edx,num

您正在将num地址 加载到edx,然后将其与100000 进行比较。该地址几乎可以肯定大于100000。但是您希望将值存储在那里,所以这样做:

    mov edx,[num]

然后再试一次。这假定num 是存储转换后的(二进制)数字的地址。正如我所说,与字符串进行比较是没有用的。

【讨论】:

    猜你喜欢
    • 2014-12-04
    • 1970-01-01
    • 2014-03-25
    • 2012-01-31
    • 2013-10-10
    • 2012-04-17
    • 2014-10-29
    • 2011-06-22
    相关资源
    最近更新 更多