我有一个赋值,我必须输入十进制数并输出二进制版本中有多少'1'位。该数字不能大于或等于4096,因此我们需要进行错误检查。我们还必须使用至少一个逻辑运算符。我已经设置了所有这些东西,但我似乎无法使它们正常工作。
我的问题: 循环似乎没有超过第8位。数字4095返回8时应返回11,而2048返回0.任何高达255的输入都返回正确的值。
我实际上从这个网站上的帖子中得到了一些想法,这就是我得到的方式。任何更多的帮助将不胜感激。
.data
inputStr: .asciiz "\nEnter a positive integer from 0-4095: "
errorStr: .asciiz "The input was not in the specified range..."
resultStr: .asciiz "The number of '1' bits: "
newline: .asciiz "\n"
.text
main:
addi $s0, $zero, 4096 #Created a variable to be used for error checking.
############Print inputStr calling for the integer.
li $v0, 4
la $a0, inputStr
syscall
############Store input as $a1.
li $v0, 5
syscall
addu $a1, $zero, $v0
############Check to see if input is valid.
bge $v0, $s0, PrintError #End if input >= 4096
############Print a blank line.
addi $v0, $zero, 4
la $a0, newline
syscall
############Call Bits procedure.
j Bits #Not a jal because Bits takes over from here basically.
############Prints the result of running Bits procedure. (How many 1's)
End:
addi $v0, $zero, 4
la $a0, resultStr
syscall
addi $v0, $zero, 1
add $a0, $zero, $v1
syscall
addi $v0, $zero, 4
la $a0, newline
addi $v0, $zero, 10
syscall
############Tells the user there was an error with their input and ends program.
PrintError:
addi $v0, $zero, 4
la $a0, errorStr
syscall
addi $v0, $zero, 10
syscall
############Bits procedure.
#This procedure uses:
#$t1 as a loop parser
#$v1 as a return variable
Bits:
move $t0, $a1
sll $t0, $t0, 24
add $t5, $zero, $zero
Loop:
beq $t5, 13, End #Case to end loop
slt $t1, $t0, $zero
andi $t2, $t1, 1 #Ands $t1 with 1
beq $t2, 1, addOne #If $t2 still equals 1, addOne
addi $t5, $t5, 1 #Increase parser by 1
sll $t0, $t0, 1
j Loop #Repeat
addOne: #Adds 1 to the output counter
addi $v1, $v1, 1 #Increment output counter
addi $t5, $t5, 1 #Increase parser by 1
sll $t0, $t0, 1
j Loop #Repeat