我正在尝试使用 MARS 模拟器将 MIPS 语言中的二进制转换为十进制。程序接受一个二进制数,然后通过乘法进行转换(左移数字的位置 $t9)。另一种说法是将每个 1 位数字乘以 2 乘以该位的幂,然后将结果相加。
我对值如何在 ascii、十进制之间存储和通信并没有很好的理解,问题是“总和”是 40,000,而不是十进制二进制数的值。我在这里做错了什么?
.data
msg1:
.asciiz "Enter a number in base 2 (-2 to quit): "
msg2:
.asciiz "\nResult: "
allOnes:
.asciiz "1111111111111111"
empty:
.space 16
newLine:
.asciiz "\n"
sum:
.space 16
sumMsg:
.asciiz "\nSUM: "
oneFound:
.asciiz "\nOne found\n"
zeroFound:
.asciiz "\nZero found\n"
.text
.globl main
main:
getNum:
li $v0,4 # Print string system call
la $a0,msg1 #"Please insert value (A > 0) : "
syscall
la $a0, empty
li $a1, 16 # load 16 as max length to read into $a1
li $v0,8 # 8 is string system call
syscall
la $a0, empty
li $v0, 4 # print string
syscall
li $t4, 0 # initialize sum to 0
startConvert:
la $t1, empty
li $t9, 16 # initialize counter to 16
firstByte:
lb $a0, ($t1) # load the first byte
blt $a0, 48, printSum
addi $t1, $t1, 1 # increment offset
subi $a0, $a0, 48 # subtract 48 to convert to int value
beq $a0, 0, isZero
beq $a0, 1, isOne
j convert #
isZero:
subi $t9, $t9, 1 # decrement counter
j firstByte
isOne: # do 2^counter
li $t8, 1 # load 1
sllv $t5, $t8, $t9 # shift left by counter = 1 * 2^counter, store in $t5
add $t4, $t4, $t5 # add sum to previous sum
move $a0, $t4 # load sum
li $v0, 1 # print int
syscall
subi $t9, $t9, 1 # decrement counter
j firstByte
convert:
printSum:
srlv $t4, $t4, $t9
la $a0, sumMsg
li $v0, 4
syscall
move $a0, $t4 # load sum
li $v0, 1 # print int
syscall
exit:
li $v0, 10 # exit system call
syscall