无符号16位十六进制字符串到十进制值

时间:2014-10-15 15:41:28

标签: assembly mips type-conversion

我试图在最多4个字符长的十六进制字符的用户输入字符串上执行无符号16位十六进制到十进制转换。我将存储str缓冲区地址的寄存器的存储单元中的字节加载到另一个寄存器中。所以我试图相应地处理每个字节。我注意到我可以取str的第一个字符并将其向左移4位,这样我就可以得到一个8位的bittring。然后,我可以获取字符串中的下一个字符,并使用8位位串执行“或”,然后将下一个字符添加到总位串的末尾。我试图找出如何实现这种关系。在我让用户输入4个字符后,我的代码挂断了。我还没有调试过这个,但我觉得我的逻辑和评论的流程应该解释我在做什么。我在这里做错了什么吗?是否有比这更短的路径?

我在这些论坛上环顾四周,我找不到任何关于尝试以这种方式转换的内容

Here I get Input
getStrInput:
li $v0, 8                   # $a0, holds input
li $a1, 5
syscall
li $v0, 0                   # reset reg $v0

la $t1, ($a0)               # save the address of the string input

# loading the byte
loadByteToStr:
li $t4, 0
beq $t3, 5, showConv        # If user has input 4 characters, branch to showConv 
addi $sp, $sp, -4           # push the stack
sw $ra 0($sp)               # save return address for safety
sw $t3, 4($sp)              # store the loop counter on stack
lb $t6, ($t1)               # Load byte from the string into temp register for function call
jal isDigit                 # check to see if it is a digit if not treat character accordingly
beqz $t3, adjustBits        # unsigned 16bit conversion from Hexa - Dec

endAdjustBits:
addi $t3, $t3, 1            # increment loop counter
jal u16Convert              # adjusted bitstring stored in $s5
addi $t1, $t1, 1            # increment address
lw $ra 0($sp)               # load original return address
addi $sp, $sp, 4            # pop the stack

j loadByteToStr             # loop

isDigit:
move $a0, $t6               # move the byte to $a0 for calculations
subi $a0, $a0, 48           # subtract ASCII 0 to see if it falls within digit range
blt $a0, 0, isChar          # check if byte is a character if not a digit
bgt $a0, 9, isChar
jr $ra                      # return to loadByteToStr


isChar:
addi $a0, $a0, 48           # reset input
subi $a0, $a0, 55           # get the hexa char value
jr $ra                      # return to loadByteToStr

# this block of code takes the first char, appends the second to it, takes the next and appends the last to it.
adjustBits: 
sll $a0, $a0, 4             # shift $a0 12 bits to make room for characters in str
add $t0, $a0, $zero         # save $a0 to $t0
beqz $t3, loadByteToStr     # if loop count is 0, load the next char before calling next function

# Get the next bytes in str
u16Convert:
or $t0, $t0, $a0            # insert next bitstring to total bitstring
beq $t3, 4, contU16         # if it is the last byte, convert the string to decimal
jr $ra

# continue conversion after creating the hex bitstring
contU16:
beq $t4, 4, showConv

addi $t0, $t0, 4            # incrememnt next 4 bits
beq $t4, 0, elem1           # treat next 4 bits in str accordingly
beq $t4, 1, elem2
beq $t4, 2, elem3
beq $t4, 3, elem4
addi $t4, $t4, 1            # increment loop counter
j contU16

0 个答案:

没有答案