Skip to content

Python examples of Binary Coded Decimal (BCD) encoding, arithmetic operations, packed vs unpacked formats, and practical applications in digital systems.

License

Notifications You must be signed in to change notification settings

maxwell-hauser/py_10_binary_coded_decimals

Repository files navigation

Chapter 10: Binary Coded Decimal (BCD)

Overview

Binary Coded Decimal (BCD) is a method of encoding decimal digits where each decimal digit (0-9) is represented by a 4-bit binary pattern. BCD is widely used in digital systems where decimal display is important, such as calculators, digital clocks, and financial systems.

Key Concepts

What is BCD?

Definition: Each decimal digit is encoded separately using 4 bits.

Decimal Digit → 4-Bit BCD
     0        → 0000
     1        → 0001
     2        → 0010
     3        → 0011
     4        → 0100
     5        → 0101
     6        → 0110
     7        → 0111
     8        → 1000
     9        → 1001

Valid and Invalid BCD Codes

Valid BCD codes: 0000 to 1001 (0-9)
Invalid BCD codes: 1010 to 1111 (A-F in hex)

1010 (10) - Invalid in BCD
1011 (11) - Invalid in BCD
1100 (12) - Invalid in BCD
1101 (13) - Invalid in BCD
1110 (14) - Invalid in BCD
1111 (15) - Invalid in BCD

BCD Encoding Examples

Example 1: Encode 247

2      4      7
↓      ↓      ↓
0010   0100   0111

BCD: 0010 0100 0111

Example 2: Encode 1984

1      9      8      4
↓      ↓      ↓      ↓
0001   1001   1000   0100

BCD: 0001 1001 1000 0100

BCD Decoding Examples

Example 1: Decode 0101 0011 1000

0101   0011   1000
 ↓      ↓      ↓
 5      3      8

Decimal: 538

Example 2: Decode 0111 0010 0110

0111   0010   0110
 ↓      ↓      ↓
 7      2      6

Decimal: 726

BCD vs Pure Binary

Comparison

Decimal Pure Binary BCD
0 0000 0000
5 0101 0000 0101
9 1001 0000 1001
10 1010 0001 0000
15 1111 0001 0101
23 00010111 0010 0011
99 01100011 1001 1001
255 11111111 0010 0101 0101

Key Differences

Pure Binary:

  • More compact (uses fewer bits)
  • More efficient for arithmetic
  • Harder to convert to decimal display
  • Example: 99₁₀ = 1100011₂ (7 bits)

BCD:

  • Less compact (uses more bits)
  • Easier to convert to decimal display
  • Simplifies decimal I/O operations
  • Example: 99₁₀ = 1001 1001 (8 bits)

Types of BCD

1. Unpacked BCD (One digit per byte)

Decimal: 247

Byte 1: 00000010 (2)
Byte 2: 00000100 (4)
Byte 3: 00000111 (7)

- Wastes 4 bits per byte
- Used in some processors for easier manipulation

2. Packed BCD (Two digits per byte)

Decimal: 247

Byte 1: 00000010 (2)
Byte 2: 01000111 (4 and 7)

OR

Byte 1: 00100100 (2 and 4)
Byte 2: 01110000 (7 and padding)

- More space-efficient
- Most common form
- Used in financial and commercial applications

BCD Arithmetic

Addition in BCD

BCD addition requires adjustment because binary addition can produce invalid BCD codes.

Rule: If result > 9 or carry generated, add 6 (0110) to correct.

Example 1: 8 + 5 = 13

   1000  (8 in BCD)
 + 0101  (5 in BCD)
 ──────
   1101  (13 in binary, but 0xD is invalid BCD!)
   
Add 6 to correct:
   1101
 + 0110
 ──────
  10011
  
Result: 0001 0011 (1 and 3 in BCD) ✓

Example 2: 25 + 17 = 42

  0010 0101  (25 in BCD)
+ 0001 0111  (17 in BCD)
──────────────
  0011 1100  (3C, but C is invalid!)
  
Adjust second digit:
       1100
     + 0110
     ──────
      10010
      
Result: 0100 0010 (42 in BCD) ✓

Subtraction in BCD

Use 10's complement method:

  1. Find 10's complement of subtrahend
  2. Add to minuend
  3. Adjust as in addition

More complex than binary subtraction, but preserves decimal alignment.

Learning Objectives

By the end of this chapter, you should be able to:

  • Encode decimal numbers in BCD format
  • Decode BCD to decimal
  • Distinguish between valid and invalid BCD codes
  • Understand packed vs unpacked BCD
  • Compare BCD with pure binary representation
  • Perform basic BCD arithmetic with adjustment
  • Explain when and why BCD is used

Python Example

Run the interactive example:

python ch10_bcd.py

What the Example Demonstrates

  1. Decimal to BCD Encoding: Converting decimal digits to 4-bit patterns
  2. BCD to Decimal Decoding: Reading BCD back to decimal
  3. Validation: Checking for invalid BCD codes
  4. BCD vs Binary Comparison: Size and representation differences
  5. Packed BCD: Two digits per byte
  6. BCD Arithmetic: Addition with adjustment
  7. Practical Applications: Real-world usage examples

Sample Output

============================================================
CHAPTER 10: Binary Coded Decimal (BCD)
============================================================

--- Example 1: Decimal to BCD Encoding ---
Decimal: 579

Digit 5: 0101
Digit 7: 0111
Digit 9: 1001

BCD: 0101 0111 1001

--- Example 2: BCD Validation ---
0101 → Valid BCD (5)
1010 → Invalid BCD (not 0-9)
0111 → Valid BCD (7)
1111 → Invalid BCD (not 0-9)
...

Real-World Applications

Financial Systems

  • Point-of-Sale (POS) Terminals: Price displays
  • Banking: Exact decimal representation (no rounding)
  • Accounting Software: Precise currency calculations
  • ATMs: Transaction amount display

Digital Displays

  • Seven-Segment Displays: Direct mapping from BCD
  • Digital Clocks: Hours, minutes, seconds in BCD
  • Calculators: Input and display in decimal
  • Meters: Utility meters, speedometers

Embedded Systems

  • Real-Time Clocks (RTC): Time stored as BCD
  • BIOS/UEFI: Date and time in BCD format
  • Smart Cards: Financial data storage
  • Industrial Controls: Setpoints and measurements

Legacy Systems

  • Mainframes: IBM systems use BCD extensively
  • COBOL Programs: Native BCD support
  • Database Systems: DECIMAL/NUMERIC types sometimes use BCD
  • Telecommunication: Signaling systems

Advantages of BCD

Easy Decimal Conversion:

  • Direct mapping: each 4 bits = one decimal digit
  • No complex division/multiplication for display

No Rounding Errors:

  • Exact decimal representation
  • Critical for financial calculations

Simple Display Logic:

  • Direct driving of 7-segment displays
  • Minimal conversion circuitry

Human-Readable:

  • Easier to debug in hex dumps
  • Clear correspondence to decimal values

Disadvantages of BCD

Storage Inefficiency:

  • Uses more bits than pure binary
  • Only 10 of 16 possible 4-bit codes used

Arithmetic Complexity:

  • Requires adjustment after addition
  • More complex hardware/software

Processing Overhead:

  • Slower than binary arithmetic
  • Additional correction steps needed

Range Limitations:

  • For same number of bits, smaller range than binary
  • 8 bits: BCD 0-99 vs Binary 0-255

BCD in Programming

C/C++ Example

// Encode decimal to BCD
uint8_t decimal_to_bcd(uint8_t decimal) {
    return ((decimal / 10) << 4) | (decimal % 10);
}

// Decode BCD to decimal
uint8_t bcd_to_decimal(uint8_t bcd) {
    return ((bcd >> 4) * 10) + (bcd & 0x0F);
}

// Example:
uint8_t bcd = decimal_to_bcd(42);  // 0x42
uint8_t dec = bcd_to_decimal(bcd);  // 42

Python Example

def decimal_to_bcd(decimal):
    """Convert decimal (0-99) to packed BCD."""
    return ((decimal // 10) << 4) | (decimal % 10)

def bcd_to_decimal(bcd):
    """Convert packed BCD to decimal."""
    return ((bcd >> 4) * 10) + (bcd & 0x0F)

# Example:
bcd = decimal_to_bcd(56)    # 0x56
dec = bcd_to_decimal(0x73)  # 73

Common Questions

Q: Why not just use binary for everything?
A: BCD eliminates conversion errors for decimal display and is essential for exact decimal arithmetic in financial systems.

Q: How do seven-segment displays use BCD?
A: A BCD-to-7-segment decoder chip directly converts BCD codes to the appropriate segment patterns.

Q: What happens if you try to display 1010 in BCD?
A: It's invalid. Most decoders will either show an error pattern or blank segments.

Q: Is BCD still used in modern systems?
A: Yes! Real-time clocks, financial systems, and embedded displays still use BCD for its exact decimal representation.

Q: How is BCD different from hexadecimal?
A: Hex uses all 16 patterns (0-9, A-F). BCD only uses patterns 0-9, with 10 of 16 patterns per digit being invalid.

Key Takeaways

  • BCD encodes each decimal digit separately using 4 bits
  • ✅ Valid BCD: 0000-1001 (0-9 only)
  • ❌ Invalid BCD: 1010-1111 (A-F not used)
  • Less efficient than binary but easier for decimal I/O
  • 💰 Essential for financial systems (exact decimal representation)
  • Arithmetic requires adjustment (add 6 when result > 9)
  • 📦 Packed BCD: 2 digits per byte; Unpacked: 1 digit per byte
  • Used in displays, RTCs, financial systems, and legacy mainframes

Practice Exercises

  1. Encode 389 in BCD
  2. Decode 0110 0010 0101 from BCD to decimal
  3. Is 0111 1011 0010 valid BCD? Explain.
  4. Convert 147₁₀ to both pure binary and BCD. Compare bit usage.
  5. Perform BCD addition: 38 + 27 (show adjustment)
  6. Why does 0x99 in BCD equal 99 in decimal, but 0x99 in binary equals 153?
  7. How many bytes are needed to store 12345 in packed BCD?
  8. Write the algorithm to detect invalid BCD
  9. Convert 0x12 0x34 0x56 (packed BCD) to decimal
  10. Explain why BCD is used in real-time clock chips

Further Study

  • Learn about excess-3 code (BCD variant)
  • Study BCD arithmetic algorithms in detail
  • Explore Gray code and other binary codes
  • Investigate EBCDIC (Extended BCD Interchange Code)
  • Learn about decimal floating-point formats

Course Navigation:
← Previous: Chapter 9 - Floating Point | Next: Chapter 11 - Coding Schemas


About

Python examples of Binary Coded Decimal (BCD) encoding, arithmetic operations, packed vs unpacked formats, and practical applications in digital systems.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages