MIPS转换32位带符号2s-com号,十进制数或8位有符号十六进制数

时间:2014-03-26 19:52:16

标签: assembly binary mips type-conversion

以交互方式读取表示32位带符号2s-补码二进制(S2CB)编号的字符串值,可以表示为32位S2CB编号的十进制数,或8位带符号的十六进制数。您的程序必须在所有三个数字基础中显示指定的值。

到目前为止,该程序会询问用户数字,但我在创建实际转换算法时遇到问题。到目前为止,该程序要求输入并确定它是否正确的样式。谁能帮帮我吗?提前谢谢。

.data

    inputString:    .asciiz "                                  "
    testString: .asciiz "Enter a number as decimal (12345), binary (%10101), or hex (0xABCDEF): "

    decDigits:  .asciiz "0123456789"
    hexDigits:  .asciiz "0123456789ABCDEF"
    binDigits:  .asciiz "000000010010001101000110011110001001101010111100110111101111"

    detectedDec:    .asciiz "Decimal input detected"
    detectedHex:    .asciiz "Hexadecimal input detected"
    detectedBin:    .asciiz "Binary input detected"
    detectedBad:    .asciiz "Invalid input detected"

    .text
begin:  li $v0, 4
    la $a0, testString
    syscall

read:   li $v0, 8
    la $a0, inputString
    li $a1, 33
    syscall

    jal isDec

    beq $v0, 0, n1
    li $v0, 4
    la $a0, detectedDec
    syscall
    j endPgm

n1: jal isHex

    beq $v0, 0, n2
    li $v0, 4
    la $a0, detectedHex
    syscall
    j endPgm

n2: jal isBin

    beq $v0, 0, bad
    li $v0, 4
    la $a0, detectedBin
    syscall
    j endPgm

bad:    li $v0, 4
    la $a0, detectedBad
    syscall
    j endPgm

###### Is Decimal? Returns 1 in $v0 if yes

isDec:  li $t0, 0
    li $t2, 0

decLoop:lb $t1, inputString($t0)
    beq $t1, 0, decDone
    beq $t1, 10, decDone
    bgt $t1, 57, notDec
    blt $t1, 48, notDec
    li $t2, 1
    addi $t0, $t0, 1
    j decLoop

notDec: li $v0, 0
    jr $ra

decDone:beq $t2, 0, notDec
    li $v0, 1
    jr $ra

######

###### Is Binary? Returns 1 in $v0 if yes

isBin:  li $t0, 1
    li $t2, 0

hasPer: lb $t1, inputString
    bne $t1, 37, notBin

binLoop:lb $t1, inputString($t0)
    beq $t1, 0, binDone
    beq $t1, 10, binDone
    bgt $t1, 49, notBin
    blt $t1, 48, notBin
    li $t2, 1
    addi $t0, $t0, 1
    j binLoop

notBin: li $v0, 0
    jr $ra

binDone:beq $t2, 0, notDec
    li $v0, 1
    jr $ra

######

###### Is Hex? Returns 1 in $v0 if yes

isHex:  li $t0, 2
    li $t2, 0

has0x:  lb $t1, inputString
    bne $t1, 48, notHex
    lb $t1, inputString + 1
    bne $t1, 120, notHex

hexLoop:lb $t1, inputString($t0)
    beq $t1, 0, hexDone
    beq $t1, 10, hexDone
    bgt $t1, 57, testAF
    blt $t1, 48, testAF
    li $t2, 1
    addi $t0, $t0, 1
    j hexLoop

testAF: bgt $t1, 70, notHex
    blt $t1, 65, notHex
    li $t2, 1
    addi $t0, $t0, 1
    j hexLoop

notHex: li $v0, 0
    jr $ra

hexDone:beq $t2, 0, notDec
    li $v0, 1
    jr $ra

######

endPgm: li $v0, 10
    syscall
enter code here

1 个答案:

答案 0 :(得分:0)

给定基数字符串的转换算法实际上非常简单。

假设基数为b,可能是21016,请考虑以下伪代码:

num := 0

while c <- input_char:
    num := num * b
    num := num + char_to_int(c)

return num