Search code examples
cbinarydivision

Binary division in C


#include "stdio.h"

int bdiv( int dividend , int divisor )
{
  int remainder = dividend ;
  int quotient  = 0 ;

  int i ;
  for( i = 0 ; i < 17 ; i++ )
    {
      remainder = remainder - divisor ;
      if( (remainder & 0x8000)  )
        {
          remainder = remainder + divisor ;
          quotient  = quotient << 1 ;
        }
      else
        quotient = ( quotient << 1 ) | 0x1 ;

      divisor = divisor >> 1 ;
    }
  return quotient ;
}

int main()
{
  int a = 7 ;
  int b = 2 ;

  printf( "%d\n" , bdiv(a,b) ) ;

}

Pseudo-Code of the algorithm I tried to implement :

START
Remainder = Dividend ;
Quotient = 0 ;
1.Subtract Divisor register from remainder and place result in remainder . 
2. Test Remainder 
2a . If remainder >= 0 shift quotient to right setting rightmost bit to 1
2b. If remainder < 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 

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 131071 for a division of 7 by 2 .


Solution

  • The second shift needs to be:

    quotient = (( quotient >> 1 ) | 0x1) ;
    

    Also, why not:

    if (remainder < 0 )
    

    ???