Packed binary-coded decimal in C

Decode a packed byte and decide when to keep BCD or convert it for arithmetic.

One decimal digit in each half of the byte

Binary-coded decimal (BCD) encodes each decimal digit separately. In this unsigned packed form, each four-bit half of the byte, called a nibble, holds one digit from 0 through 9. The high nibble holds tens and the low nibble holds ones.

decimal 42 → 0100 | 0010 → packed byte 0x42

The same byte interpreted as an unsigned binary integer means 66, since 4 × 16 + 2 = 66. As BCD, it means 4 × 10 + 2 = 42. Just 100 of the 256 byte patterns have two valid BCD digits. For example, 0x4a has a low nibble of 10 and fails validation.

Ordinary C arithmetic follows the binary interpretation of the byte. It gives 0x09 + 0x01 == 0x0a. To get the BCD result 0x10, decode both bytes, add the decimal values as integers, then encode the sum.

Where BCD still shows up

The PC/AT BIOS clock interface

A program running in a DOS-era environment could call the BIOS with INT 1Ah. On a PC/AT-compatible BIOS, AH=02h reads hours, minutes, and seconds as packed BCD in CH, CL, and DH. Check the carry flag for failure before decoding those registers. AH=04h reads the century, year, month, and day in CH, CL, DH, and DL. IBM BIOS Interface Technical Reference, INT 1Ah

With AH=06h, the caller supplies an alarm time as packed BCD in CH, CL, and DH. When the clock raises hardware interrupt IRQ 8, the PC/AT BIOS interrupt service routine at vector 70h handles it. For an alarm event it invokes the user alarm handler at INT 4Ah. IBM PC/AT BIOS listing, RTC alarm and interrupt handler

What DOS-era programs did with BCD

Clock display and arithmetic. A program displaying 18:07:42 can take the two digits from each BIOS clock byte, 0x18, 0x07, and 0x42, and turn each digit into a character by adding it to '0'. For elapsed-time arithmetic, decode to binary integer seconds first. The published MS-DOS 1.25 clock I/O routines used AAD to combine unpacked digits when reading and AAM to split them before packing when writing. That conversion took place inside the driver. MS-DOS 1.25 clock I/O source

Business arithmetic. Borland offered TURBO-BCD, a version of Turbo Pascal 3 for DOS with BCD arithmetic for Real values. Decimal arithmetic can represent a value such as 0.1 exactly when it has enough precision and exponent range. Microsoft BASIC PDS 7 also offered CURRENCY, which fixed the scale at four decimal places. That gave business programs a fixed decimal unit for exact amounts that fit. Borland Turbo Pascal 3 reference, Chapter 23 · Microsoft BASIC numeric format notes

Native x86 decimal instructions

InstructionsWhat they do64-bit mode
DAA, DASAdjust a packed two-digit result in AL after binary addition or subtraction.Invalid
AAA, AASAdjust after adding or subtracting unpacked BCD digits, where each digit occupies a byte.Invalid
AAM, AADSplit a binary result into unpacked digits, or combine unpacked tens and ones as 10 × AH + AL.Invalid
FBLD, FBSTPConvert between x87 extended precision and its own 10-byte format holding 18 digits and a sign. FBSTP rounds to an integer using the x87 rounding control.Valid

The six integer adjust instructions remain defined in legacy and compatibility modes. For packed addition, ADD on 0x09 and 0x01 puts 0x0a in AL. DAA adjusts it to packed 0x10. Intel instruction reference

For a total already stored in packed BCD, start at the least significant byte. Adjust each sum with DAA, then use ADC to carry into the next byte. The low byte holds the tens and ones, so its carry adds one hundred to the total. Microsoft MASM 6.0 programmer’s guide, §6.4.2.2

Try a decimal carry

Predict AL after ADD on 0x99 and 0x01. Then predict AL and the carry flag after DAA.

Check the instruction trace

After ADD, AL is 0x9a. After DAA, it is 0x00 with carry set. In a two-byte total, the next byte receives that carry and becomes 0x01 if its two input bytes were zero.

Choose the encoding and the scale

BCD says how the digits are stored. Fixed-point says where the point goes. A packed decimal field with two implied fractional digits is both BCD and fixed-point. You could decode 12 34 5D from the COBOL example to the ordinary binary integer -12345 and keep exactly the same meaning, −123.45.

When exact decimal increments matter and values need different scales, explore decimal floating-point. IEEE 754 decimal formats pair a coefficient with a decimal exponent. You still need a rounding rule for results such as 1/3. IEEE 754-2019 §3.5

Exercises

1. Read a clock register

The PCF85263A seconds register returns 0xd9. Give the oscillator-stop bit and the seconds digits. Would the register value 0x69 pass both the BCD digit check and the seconds range check?

Check the register interpretation

0xd9 & 0x80 is nonzero, so the oscillator-stop bit is set. 0xd9 & 0x7f is 0x59, which decodes to 59. Treat the reading as suspect because of the stop flag. 0x69 has two valid digits and fails the seconds range check.

2. Write a two-digit codec

Write bool bcd_byte_decode(uint8_t packed, unsigned *result) and bool bcd_byte_encode(unsigned value, uint8_t *result). Use shifts and masks to unpack the digits. Use division and remainder by ten to get tens and ones when encoding.

Each function receives a valid output pointer. Return true and write the result on success. Reject a nibble above 9 or a value above 99 and leave the output alone. Round-trip every value from 0 to 99, then try decoding 0xa9 and 0x9a and encoding 100.

Compare with a runnable solution

Save the code as bcd.c.

#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

/* Decode two packed BCD digits into an integer using a valid result pointer.
 * Return false and leave the result unchanged if either digit exceeds 9.
 */
bool bcd_byte_decode(uint8_t packed, unsigned *result)
{
    const unsigned tens = packed >> 4;
    const unsigned ones = packed & 0x0Fu;

    if (tens > 9u || ones > 9u) {
        return false;
    }

    *result = tens * 10u + ones;
    return true;
}

/* Pack an integer from 0 through 99 into two BCD digits using a valid
 * result pointer. Return false and leave the result unchanged above 99.
 */
bool bcd_byte_encode(unsigned value, uint8_t *result)
{
    if (value > 99u) {
        return false;
    }

    const unsigned tens = value / 10u;
    const unsigned ones = value % 10u;
    *result = (uint8_t)((tens << 4) | ones);
    return true;
}

int main(void)
{
    unsigned value;
    if (!bcd_byte_decode(0x42, &value)) {
        return 1;
    }
    printf("%u\n", value);

    uint8_t packed;
    if (!bcd_byte_encode(value, &packed)) {
        return 1;
    }
    printf("0x%02X\n", (unsigned)packed);

    const bool rejected = !bcd_byte_decode(0x4A, &value) && value == 42u;
    assert(rejected);
    return rejected ? 0 : 1;
}
cc -std=c11 -Wall -Wextra -pedantic bcd.c -o bcd
./bcd
42
0x42

3. Pick a representation for each job

A data logger reads a BCD clock, archives voltages to the nearest millivolt, and fits a calibration curve. Where would you use BCD, scaled integers, and floating-point?

Compare one design

Decode BCD at the clock interface. Store each archived voltage as an integer count of millivolts. Use double for the curve fit if its precision meets the error budget, then apply the chosen rounding rule when a result returns to the archive.