Skip to main content

C program: sum of two 8-bit BCD numbers

Short answer

Unpack each BCD byte into tens and units digits. Add units digits; if sum >9, subtract 10 and increment tens. Add tens digits; if sum >9, subtract 10 and set carry byte (53H) to 1. Pack the two-digit sum into 52H.

Write a program using C-programming language to find the sum between two 8-bit BCD data stored in RAM locations 50H and 51H and store the BCD sum at RAM locations 52H and 53H.

Each byte holds two packed BCD digits (e.g. 68H means 68). The units and tens digits are added separately and adjusted: any digit above 9 is reduced by 10 with a carry to the next digit. The sum goes to 52H, and the hundreds digit (carry) to 53H.

#include <reg51.h>
#include <absacc.h>

#define NUM1   DBYTE[0x50]      /* first packed BCD number   */
#define NUM2   DBYTE[0x51]      /* second packed BCD number  */
#define SUM    DBYTE[0x52]      /* BCD sum (two low digits)  */
#define CARRY  DBYTE[0x53]      /* 01 if the sum exceeds 99  */

void main(void)
{
    unsigned char lo, hi;

    lo = (NUM1 & 0x0F) + (NUM2 & 0x0F);     /* add the units digits */
    hi = (NUM1 >> 4)   + (NUM2 >> 4);       /* add the tens digits  */

    if (lo > 9) {                           /* decimal adjust units */
        lo -= 10;
        hi++;                               /* carry into tens      */
    }
    CARRY = 0;
    if (hi > 9) {                           /* decimal adjust tens  */
        hi -= 10;
        CARRY = 1;                          /* hundreds digit = 1   */
    }
    SUM = (hi << 4) | lo;                   /* pack the two digits  */

    while (1);                              /* stop */
}

Examples (tested in an 8051 simulator): 68H + 59H gives 52H = 27H, 53H = 01H (127); 45H + 38H gives 83H, 00H; 99H + 99H gives 98H, 01H (198).

✓ Answer checked by Claude Opus 5.5 (high effort)

All Embedded System chapter 9 questions →