/* C program for BCD / Integer conversions */ #include #include /* Function prototypes */ unsigned int 8 bcd2int(unsigned 4 *bcd); int int2bcd(int i, int bcd[]); /**************************************************************************** /* main function ****************************************************************************/ int main(int argc, char* argv[]) { int i; /* Store an integer value */ int bcd[2]; /* Store a two-dogit BCD value */ /* (MSD is bcd[1], LSD is bcd[0]) */ int bcdcount[2] = { 0, 0 }; /* Stores two-digit BCD count */ /* This loop tests the bcd2int and int2bcd functions */ for (;;) { /* Convert bcdcount from BCD to integer */ i = bcd2int(bcdcount); /* Convert integer back to BCD */ int2bcd(i, bcd); /* Write out the results */ printf("%d%d => %d => %d%d\n", bcdcount[1], bcdcount[0], i, bcd[1], bcd[0]); /* Increment the BCD counter */ if ( bcdcount[0]++ == 9 ) { bcdcount[0] = 0; if ( bcdcount[1]++ == 9 ) break; } } /* This is the end of the program */ exit (EXIT_SUCCESS); } /**************************************************************************** /* Convert a two-digit binary-coded decimal (BCD) number to an integer ****************************************************************************/ int bcd2int(int bcd[]) { return ( 10 * bcd[1] + bcd[0] ); } /**************************************************************************** /* Convert an unsigned integer to a two-digit BCD number ****************************************************************************/ void int2bcd(int i, int bcd[2]) /* "i" is an unsigned integer, assumed to be less than 128 */ { int bit; /* Loop variable - counts bits */ int Carry; /* Carry from BCD digit 0 to 1 */ bcd[0] = 0; /* Reset the BCD digits to 0 */ bcd[1] = 0; for (bit = 0; bit < 8; bit++ ) { /* Assume 8 bits */ if ( bcd[0] < 5 ) { /* Bottom BCD digit */ bcd[0] *= 2; Carry = 0; } else { bcd[0] = (bcd[0] - 5) * 2; Carry = 1; } if ( i & 0x80 ) /* Add the top bit of i */ bcd[0]++; /* to the bottom BCD digit */ i *= 2; /* Shift i to the left */ if ( bcd[1] < 5 ) { /* Top BCD digit (no carry) */ bcd[1] *= 2; } else { bcd[1] = (bcd[1] - 5) *2; } bcd[1] += Carry; } }