/****************************************************/
       /*           NONRESTORING DIVISION                  */
       /*   Source code written by: A. Yavuz Oruç          */
       /*            E-mail: yavuz@eng.umd.edu             */                
       /*          Last revised:  October 1998             */
       /*  Input:  32-bit dividend, and 16-bit divisor     */  
       /*  Output: 16-bit quotient, and 16-bit remainder   */      
       /*                                                  */
       /****************************************************/

// AYO: This program computes a 16-bit  remainder and 16-bit quotient (p,q) upon receiving 
// a 32-bit dividend  (p,q), and a 16-bit divisor n, both expressed in 2's complement notation.
// It uses nonrestoring division with positive operands. Negative operands are handled
// by first converting them to unsigned numbers. Both operands are entered in hexadecimal.

#include <iostream.h>
#include <stdio.h> 
#include <limits.h> 
void main(void)
{int p,q,i,n;
 Boolean sp,sn,sd,sq,F = 0;	
  while(true)
  { 
  //AYO: Here read in the dividend and divisor in hex. dd = qxn + r
  printf("\nEnter upper half of dividend: ");
  scanf("%04X", &p);
  printf("\nEnter lower half of dividend: ");
  scanf("%04X", &q);
  printf("Enter divisor: ");
  scanf("%04X", &n);
  printf("\nFor dividend, you entered: "); 
  printf("%04X",p); printf("%04X",q);
  printf("\nFor divisor, you entered: "); 
  printf("%04X",n);
  printf("\n");  printf("\n"); 
 //AYO: Extract the signs of divisor and dividend. 
  sn = (n & 0x8000) >> 15;  sp = sd = (p & 0x8000) >> 15;
 //AYO: Negate the dividend if it is negative.
  if(sp == 1) {p = ~p + (q == 0); q = 1 + ~q; sp = 0;}
 //AYO: Negate the divisor if it is negative.
  if(sn == 1) {n = -n;}

 //AYO: Begin the actual division.
 for(i = 1; i <= 16; i++)
  {
   if (sp == 0) 
    {//AYO: subtract n from 2 x dd.
     p =  ((p << 1) | ( (q >> 15) & 0x0001)) - n; 
    }
   else 
    {//AYO: add n to 2 x dd. 
     p =  ((p << 1) |  ( (q >> 15) & 0x0001))  + n; 
   }
      sp =  (p & 0x8000) >> 15;  
      q = ( q << 1) | ((~sp) & 0x0001); 
   }
   
   //AYO: Correct remainder
    sq = (q & 0x8000) >> 15;
    if ((!sq) && sp )  {p = p + n;}
    
   //AYO: Correct quotient
   if (sd != sn) q = -q;
  
   //AYO: Overflow
  if (n == 0 || sq) F = 1; 

    printf("\nThe quotient is: ");   printf("%04X",q);  
    printf("\nThe remainder is: ");  printf("%04X",p);
    if (F) {printf("\n\nThe division is resulted in an overflow;");
    printf("\nEither the quotient is too large or divisor is 0."); } 
    printf("\n");
  }

}
   

Return to my home page

Return to software page