在MIPS中使用syscall 8验证用户输入 [英] Verifying user input using syscall 8 in MIPS

查看:492
本文介绍了在MIPS中使用syscall 8验证用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力寻找一种有效的方法,以使用syscall 8来检查用户是否输入了只有数字(0〜9)的有效输入

I'm struggling to figure an efficient way to check if the user entered a valid input which is only numbers (0~9), using syscall 8

输入为4个字节长(1个字),
我需要检查每个字节(字符)是否为数字,

the input is 4 bytes long (1 word),
and I need to check for each byte (char) if it's a number or not,

我想尝试运行一个循环,并检查其ascii值是否低于48("0" ascii decimel值),
或高于57("9" ascii分度值),

I thought of trying to run through a loop and check if its ascii value is lower than 48 ('0' ascii decimel value),
or higher than 57('9' ascii decimel value),

这是一种有效的方法吗?
如果是这样,那么在MIPS中实现这种if语句的正确方法是什么?
例如

Is this an efficient way of doing this?
and if so, what's the right way to implement such if statement in MIPS?
for example

if (x < 48) or (x > 57) {...}

*注意:假设我有一个标志来知道在哪里停止循环

*Note: assume I do have a flag to know where to stop the loop

*这是代码的一部分,以使其更加清晰:

* this is a segment of the code, to make it clearer:

.data

    number:
    .word w1

.text

.globl main

main:

    la $a0, number      # read the number input from user
    li $a1, 6           # buffer set to max of 4 bytes (32 bits),
                       # assuming the input is no more than the length of a word,
                       # + 2 reserved bytes
    li $v0, 8
    syscall

推荐答案

尝试一下:

    lbu   $t0, x        # read next byte
    sltiu $t1, $t0, 48  # t1 = (x < 48) ? 1 : 0
    bnez  $t1, fail
    sltiu $t1, $t0, 58  # t1 = (x < 58) ? 1 : 0
    beqz  $t1, fail
    # we now know that 48 <= $t1 <= 57
    . . .
    . . .
fail: # input byte was not a digit if we get to here

这篇关于在MIPS中使用syscall 8验证用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆