0

I have an assignment where I have to take in a decimal number and output how many '1' bits are in the binary version. The number can't be greater than or equal to 4096 so we need error checking. We also have to use at least one logical operator. I have all of these things set up, but I can't seem to get them to work properly.

My Problem: The loop doesn't seem to make it past the 8th bit. The number 4095 returns 8 when it should return 11, and 2048 returns 0. Any input up to 255 returns the correct value.

I have actually gotten some ideas from previous posts on this site and that is how I got as far as I have. Any more help will be greatly appreciated.

.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
  • Nevermind, I fixed it. All I did was randomly switch the sll command in the Bits procedure to shift by 20, not 24. I don't know why this worked so if someone could chime in it would be much appreciated. – user3508761 Apr 07 '14 at 23:04
  • 1
    Probably because `log2(4096)` is 12, and 32-12 == 20. – Michael Apr 08 '14 at 05:44

0 Answers0