title: How to count the number of binary 1's in MIPS code?
body: <p>First, I started this work by typing up a C-code that counted the number of binary 1's in a positive number. I found it easier to type C-code first and then try to convert it. My C-code is as follows:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  int main(void)
  {
     int num;
     int remainder;
     int one_count=0;
     int input_num;
  
     printf("Please enter a positive integer: ");
     scanf("%d",&amp;num);
     input_num = num;
  
     while (num &gt; 0)
     {
      remainder = num % 2;
      if(remainder == 1)
        {
         one_count++;
        }
       printf("%d\n",num);
       num = num/2;
  
     }
     printf("The number of 1's in %d",input_num);
     printf(" is %d\n.",one_count);
  
   return 0;
  }
  </code></pre>
  
  <p>Now, I tried to convert this to MIPS without using pointers but I keep getting zero as an answer even though I think my logic is right. I pretty much just went down the line in C-code and attempted to convert it into MIPS. I am suppose to use $sp, but for now I am just trying to get it to count the right number and then I will attempt to implement the stack. My attemps at MIPS code is as follows:</p>
  
  <pre><code>    .data
     Prompt1:.asciiz "Please enter a positive integer: "
     Prompt2:.asciiz "in "
     Prompt3:.asciiz " is "
     Result: .asciiz "The number of 1's "
      .text
    main:
      li $v0,4
      la $a0, Prompt1
      syscall
  
   #get user entered number
   li $v0,5
   syscall
   move $s0,$v0
   move $s1,$v0
  
   li $v0,4
   la $a0, Result
   syscall
  
   li $v0,4
   la $a0, Prompt2
   syscall
  
  
   move $a0,$s1
   li $v0,1
   syscall
  
   li $v0,4
   la $a0, Prompt3
   syscall
  
   move $a0,$t4
   li $v0,1
   syscall
  
  
  
  
  onecount:
  
    li $t5,1            #to set remainder equal to 1
    li $t2,2            # to divide num by two
  
  
    ble $s1,$0,exit     #if $s1(num &lt;=0), jump to exit
    rem $s2, $s0,$t2    # hold modulus in $s2
  
    bnez $s2, increment #if ($s2(remainder) != 0), jump to increment and do        .                                                    # one_count++
    div $s1,$t2         # num = num /2
  
  
  increment:
    addi $t4,$t4,1      # one_count++ to count number of 1's in $t4 
  
    j onecount          #jump back to one count until num equal to zero
  
  exit:
  
   li $v0,10
   syscall
  </code></pre>
  
  <p>Right now, all this output gives me is zero and it continually runs. I believe I set it up correctly to how the C-code is set up but obviously not. Any help would be great if anyone knows where I am going wrong.</p>