2015-11-17 39 views
1

我正在寫一個程序,它讀取4個十六進制數字,表示一個無符號整數,然後它濃縮$ t1中的這些數字,最後它計算並顯示小數。如何使用or和sll打包(凝結)字符串的字節?

我已經完全理解了理論上的解決方案,但是由於這是我的第一個程序,所以我無法使用mips。目前,我無法存儲字符串的字節。這裏是我的代碼到目前爲止:

.data 
msg1: .asciiz "Enter the hexadecimal : " 
newline: .asciiz "\n" 
.text 

main: 
#Print string msg1 
li $v0 ,4 # print_string syscall code = 4 
la $a0,msg1 #load the adress of msg 
syscall 

# Get input A from user and save 
li $v0,8  # read_string syscall code = 8 
syscall 
move $t0,$v0  # syscall results returned in $v0 

li $v0,10 
syscall 

我知道我會使用磅Rdest,地址在某些時候。但是,如果情況如此,我是不是必須逐一讀取字符串的每個數字?

+1

是的,您需要逐一讀取每個數字。在每一步中,將部分結果左移4位,並根據新數字填入低4位。 – Jester

+0

謝謝@Jester。你能告訴我怎麼做?我可以使用字符訪問功能,例如: la $ t0,字符串 磅$ a0,($ t0) li $ v0,11 系統調用 –

+0

您不需要打印它(這是什麼系統調用#11 )你可以在'lb'處停下來。你可能會想要一個循環。 – Jester

回答

1
.data 
    msg1: .asciiz "Enter the hexadecimal : " 
    buffer: .space 10 
.text 

main: 
    #Print string msg1 
    li $v0 ,4 # print_string syscall code = 4 
    la $a0,msg1 #load the adress of msg 
    syscall 

    # Get input A from user and save 
    la $a0, buffer # address 
    li $a1, 10  # length 
    li $v0,8  # read_string syscall code = 8 
    syscall 

    li $t0, 0    # result 
loop: 
    lb $t1, ($a0)   # fetch char 
    beq $t1, $0, done  # zero terminator? 
    addiu $t1, $t1, -10  # line feed? 
    beq $t1, $0, done 
    addiu $t1, $t1, -38  # convert digit 
    sltiu $t2, $t1, 10  # was it a digit? 
    bne $t2, $0, append  # yes 
    # add validation and upper case here as needed 
    addiu $t1, $t1, -39  # convert lower case letter 
append: 
    sll $t0, $t0, 4   # make room 
    or $t0, $t0, $t1   # append new digit 
    addiu $a0, $a0, 1  # next char 
    j loop 

done: 
    move $a0, $t0   # print result 
    li $v0, 1 
    syscall 

    li $v0,10 
    syscall