title: Counting the number of digits in a 32-bit signed integer using base 2 returns 32 instead of 31
body: <p>Part of an assignment for my systems programming class asks us to write an assembly module that returns the number of digits in a 32-bit integer given a base in the range of 2 to 36 inclusive. <strong>Everything works fine except for one case</strong>. When I use the <strong>maximum</strong> signed positive 32-bit value <code>0x7FFFFFFF</code> and a base of <code>2</code>, the code returns <strong>32</strong> instead of <strong>31</strong> as the number of digits.</p>
  
  <p>As a solution, I thought about handling this case by including instructions to check if the <code>num</code> argument is equal to <code>0x7FFFFFFF</code> and returning 31 if so. However, I'm not sure if that approach would be correct.</p>
  
  <p>I'm using a "do-while loop" type algorithm to solve the problem.</p>
  
  <p>Function prototype: <code>int numOfDigits( long num, int base );</code></p>
  
  <pre><code>.global numOfdigits
  
  .section ".text"
  
  numOfDigits:
  
      save   %sp, -96, %sp
  
      clr    %l0         ! digits = 0
  
      mov    %i0, %o0    ! num is first argument to .div
      mov    %i1, %o1    ! base is second argument to .div
  
  loop:
  
      call   .div        ! %o0 = %o0 / %o1
      nop
  
      inc    %l0         ! ++digits
  
      cmp    %o0, 0      ! while ( num != 0 )
      bne    loop
      nop
  
      mov    %l0, %i0    ! copy digits value into return register
  
      ret
      restore
  </code></pre>