title: Binary division in C
body: <pre><code>#include "stdio.h"
  
  int bdiv( int dividend , int divisor )
  {
    int remainder = dividend ;
    int quotient  = 0 ;
  
    int i ;
    for( i = 0 ; i &lt; 17 ; i++ )
      {
        remainder = remainder - divisor ;
        if( (remainder &amp; 0x8000)  )
          {
            remainder = remainder + divisor ;
            quotient  = quotient &lt;&lt; 1 ;
          }
        else
          quotient = ( quotient &lt;&lt; 1 ) | 0x1 ;
  
        divisor = divisor &gt;&gt; 1 ;
      }
    return quotient ;
  }
  
  int main()
  {
    int a = 7 ;
    int b = 2 ;
  
    printf( "%d\n" , bdiv(a,b) ) ;
  
  }
  </code></pre>
  
  <p>Pseudo-Code of the algorithm I tried to implement : </p>
  
  <pre><code>START
  Remainder = Dividend ;
  Quotient = 0 ;
  1.Subtract Divisor register from remainder and place result in remainder . 
  2. Test Remainder 
  2a . If remainder &gt;= 0 shift quotient to right setting rightmost bit to 1
  2b. If remainder &lt; 0 , restore the original value of the remainder register . Also shift the quotient register to the left setting the new least significant bit to 0 .
  3. Shift the divisor right 1 bit .
  4. is it the 33rd repetition ( for 32 bit division ) ? No : GOTO 1 
     Yes : STOP 
  </code></pre>
  
  <p>I wrote this program for binary division in C for 16 bit division and it's not working . Can anyone suggest me what's not working ? 
  It is giving output as <code>131071</code> for a division of 7 by 2 . </p>