Binary-Coded Decimal (BCD) Encoding
Learn Binary-Coded Decimal encoding where each decimal digit is stored as a 4-bit binary value. Understand packed vs unpacked BCD and real-world hardware uses.
Detailed Explanation
Binary-Coded Decimal (BCD) represents each decimal digit individually as a 4-bit binary value, rather than converting the entire number to binary. While less space-efficient than pure binary, BCD avoids rounding errors inherent in binary representation and simplifies decimal display.
How BCD works:
Each decimal digit (0-9) is encoded in 4 bits:
| Digit | BCD | Digit | BCD |
|---|---|---|---|
| 0 | 0000 | 5 | 0101 |
| 1 | 0001 | 6 | 0110 |
| 2 | 0010 | 7 | 0111 |
| 3 | 0011 | 8 | 1000 |
| 4 | 0100 | 9 | 1001 |
Values 1010 through 1111 (10-15) are invalid in BCD.
Example — encoding 4729 in BCD:
4=01007=01112=00109=1001
BCD: 0100 0111 0010 1001
Compare with pure binary: 4729₁₀ = 1001001111001₂ (13 bits vs. 16 bits for BCD). BCD uses more space but preserves the decimal structure.
Packed vs. unpacked BCD:
- Packed BCD: Two decimal digits per byte (as shown above). More space-efficient.
- Unpacked BCD: One decimal digit per byte, with the upper 4 bits set to zero (or sometimes to 0011 for ASCII digits). Easier to process but uses twice the space.
Where BCD is used today:
- Financial systems: BCD avoids the floating-point errors that make 0.1 + 0.2 != 0.3 in binary. COBOL, which powers most banking systems, uses BCD internally.
- Real-time clocks: Most hardware RTCs (like the DS1307) store time in BCD. Reading "12:30:45" from the chip gives you bytes
0x12,0x30,0x45in BCD. - Digital displays: Seven-segment LED/LCD displays naturally map to BCD — each digit drives one display element.
- SQL DECIMAL type: Many databases use BCD-like encoding for exact decimal arithmetic.
Use Case
Financial software engineers use BCD encoding in banking systems to perform exact decimal arithmetic on monetary values, avoiding the rounding errors inherent in binary floating-point.
Try It — Number Base Converter
Related Topics
Convert Binary to Decimal
Binary (Base 2) → Decimal (Base 10)
Convert Decimal to Binary
Decimal (Base 10) → Binary (Base 2)
IEEE 754 Floating Point Binary Representation
Decimal (Floating Point) → Binary (IEEE 754)
Convert ASCII Characters to Binary
ASCII Text → Binary (7/8-bit)
Convert Hexadecimal to Decimal
Hexadecimal (Base 16) → Decimal (Base 10)