/****************************************************/
       /*         BINARY-CODED-DECIMAL ADDITION            */
       /*     Source code written by: A. Yavuz Oruç        */
       /*            E-mail: yavuz@eng.umd.edu             */  
       /*          1st Version:  October 1998              */              
       /*          Last revised: November 1999             */
       /*  Input:  Two 4-digit BCD operands                */  
       /*  Output: 4-digit sum with a carry                */      
       /*                                                  */
       /****************************************************/


// AYO: This program computes a 4-digit  BCD sum upon receiving 
// two unsigned 4-digit BCD operands p and r, expressed in hexadecimal
// notation. The program first biases the second operand, and selectively 
// removes the bias from the sum digits if they are overbiased.

#include <iostream.h>
#include <stdio.h> 
#include <limits.h> 

void main(void)
{ unsigned int  p,r;
  Boolean ebit,d1,d2,d3,d4; //AYO: ebit flags an illegal operand.
  //AYO: If Boolean does not work on your compiler, change it to bool.
  while(true)
  {ebit = 0,d1 = 0,d2 = 0,d3 = 0,d4 = 0; 
 //AYO: Here read in the augend and addend in hex.
  printf("\nEnter augend (first operand, r) in hexadecimal: ");
  scanf("%04X", &r);
  printf("Enter addend (second operand, p) in hexadecimal:");
  scanf("%04X", &p);
  printf("\nFor augend, you entered: "); 
  printf(" "); printf("%04X",r); 
  printf("\nFor addend, you entered: "); 
  printf(" "); printf("%04X",p);
  if((r & 15) > 9 || ((r >> 4) & 15) > 9 || ((r >> 8) & 15) > 9 || ((r >> 12) & 15) > 9)
  {printf("\nYour augend is not a valid BCD number");  printf("\n"); ebit = 1;}
  if ((p & 15) > 9 || ((p >> 4) & 15) > 9 || ((p >> 8) & 15) > 9 || ((p >> 12) & 15) > 9)
  {printf("\nYour addend is not a valid BCD number");  printf("\n"); ebit = 1;} 
  if(ebit == 0)
 {//AYO: Here bias  the augend.
  r = r + 0x6666; 
  //AYO: Here record the digits which need to be debiased.
  d1 =  ((p & 15)  + (r & 15)) < 16;
  d2 = (((p >> 4) & 15)  + ((r >> 4) & 15)) +  !d1 < 16;
  d3 = (((p >> 8) & 15)  + ((r >> 8) & 15)) +  !d2 < 16;
  d4 = (((p >> 12) & 15) + ((r >> 12) & 15)) + !d3 < 16;
 //AYO: In actual hardware BCD addition, di's are the complements of the  carries from
 //the 4th,8th,12th, and 16th bit additions in a 16-bit binary adder. 
 
 //AYO: Here sum the addend with the biased augend.
  r = r + p;
 //AYO: Here selectively remove the bias from the four digits.
 if(d1) r = r + (~6) + 1; 
 if(d2) r = r + ~(6 << 4) +  1; 
 if(d3) r = r + ~(6 << 8) +  1; 
 if(d4) r = r + ~(6 << 12) + 1; 
 printf("\nThe BCD sum, r+p, is:   "); 
 printf("%01d",!d4); printf(","); printf("%04X",r);
 printf("\n");
 }
 
}
 
} 


 


Return to my home page

Return to software page