Programming Search⌘K

Conceptadvanced

Binary-coded decimal

Also called BCD, packed BCD, packed decimal, unpacked BCD, zoned decimal, COMP-3, PACKED-DECIMAL, 8421 code, NBCD.

Binary-coded decimal stores each decimal digit in its own four or eight bits. Packed BCD puts two digits in a byte, often with a sign nibble, and an addition needs a decimal adjust step.

Applies to
core-languages

Idea

Binary-coded decimal (BCD) is "a class of binary encodings of decimal numbers where each digit is represented by a fixed number of bits, usually four or eight"1. The usual code gives each digit its own 4-bit binary value, so 0 is 0000 and 9 is 1001. Wikipedia calls this code BCD 8421 and says that it "is the most common encoding"1. The six patterns from 1010 to 1111 are not valid digits.

Wikipedia names two main forms. The term unpacked BCD "usually implies a full byte for each digit (often including a sign), whereas packed BCD typically encodes two digits within a single byte"1. A third form, zoned decimal, stores one digit in the low four bits of a byte and sets the high four bits so that the byte is the character code of the digit1.

def packed(n):
    digits = str(abs(n)) + ("D" if n < 0 else "C")
    if len(digits) % 2:
        digits = "0" + digits
    return bytes.fromhex(digits)


def zoned_ascii(n):
    return bytes(0x30 | int(d) for d in str(n))


def unpack(b):
    h = b.hex().upper()
    value = int(h[:-1])
    return -value if h[-1] == "D" else value


print("127 in 8421 BCD:", " ".join(f"{int(d):04b}" for d in "127"))
print("127 in binary:", f"{127:b}")
print("packed 127:", packed(127).hex(" ").upper())
print("packed -127:", packed(-127).hex(" ").upper())
print("packed 2024:", packed(2024).hex(" ").upper())
print("unpack 12 7D:", unpack(bytes.fromhex("127D")))
print("zoned ASCII 127:", zoned_ascii(127).hex(" ").upper())
Output
127 in 8421 BCD: 0001 0010 0111
127 in binary: 1111111
packed 127: 12 7C
packed -127: 12 7D
packed 2024: 02 02 4C
unpack 12 7D: -127
zoned ASCII 127: 31 32 37

The hexadecimal form of a packed BCD value shows the decimal digits, because each hexadecimal digit is one nibble. C and D in the last nibble are the sign.

How it works

The sign nibble. In packed BCD, "The lower nibble of the rightmost byte is usually used as the sign flag"1. The preferred codes are C for plus and D for minus, and F means unsigned1. "In packed BCD, the number 127 is represented by 0001 0010 0111 1100 (127C) and −127 is represented by 0001 0010 0111 1101 (127D)."1 Since a byte has two nibbles and one nibble is the sign, "a word of n bytes can contain up to 2n − 1 decimal digits"1. So 2024, with four digits and a sign, needs three bytes and a leading 0, as the block shows.

Zoned decimal. In zoned decimal, the zone bits make each byte a character. "ASCII systems use a zone value of 0011 (hex 3), giving character codes 30 to 39 (hex)."1 EBCDIC systems use the zone F for the digits, and the zone of one byte can hold the sign1.

Addition. A BCD adder first adds in binary, then corrects each digit. "Conversion of the simple sum of two digits can be done by adding 6 (that is, 16 − 10) when the five-bit result of adding a pair of digits has a value greater than 9."1 For example, 9 + 8 is 10001 in binary. Adding 6 gives 0001 0111, which is 17 in BCD1. The x86 DAA instruction does this correction for a byte: it "Adjusts the sum of two packed BCD values to create a packed BCD result"2. Its rule adds 6 when the low digit is more than 9 or the auxiliary carry flag is set, and adds 60 hexadecimal when the old value was more than 99 hexadecimal or the carry flag was set2.

Subtraction. "Subtraction is done by adding the ten's complement of the subtrahend to the minuend."1 The ten's complement of a 3-digit number is 999 minus the number, plus 11. This is the decimal form of Two's complement.

def bcd_add_byte(a, b):
    s = a + b
    low_carry = (a & 0x0F) + (b & 0x0F) > 0x0F
    if (s & 0x0F) > 9 or low_carry:
        s += 0x06
    if s > 0x99:
        s += 0x60
    return s & 0xFF, s > 0xFF


for a, b in ((0x09, 0x08), (0x45, 0x38), (0x99, 0x01)):
    r, carry = bcd_add_byte(a, b)
    print(f"{a:02X} + {b:02X} = {r:02X} carry {'yes' if carry else 'no'}")
Output
09 + 08 = 17 carry no
45 + 38 = 83 carry no
99 + 01 = 00 carry yes

The function follows the rule of DAA for two packed BCD bytes, but it tests the sum in place of the flags of the processor.

In languages

LanguageVerdictNote
PythonIdiom
C++Idiom
JavaIdiom
CIdiom
C#Idiom
JavaScriptIdiom
TypeScriptIdiomTypeScript has no BCD type, so a program packs the nibbles with shifts and masks, as in JavaScript. No example file exists.
GoIdiom
RustIdiom
KotlinIdiomKotlin has no BCD type, so a program packs the nibbles with shl, or and and on Int and Byte values. No example file exists because kotlinc is not installed.
SQLAbsentStandard SQL has no BCD type. No example file exists.
BashIdiomBash has no BCD type, but arithmetic expansion has shifts and masks, and printf with %X shows the packed digits. No example file exists.
PowerShellIdiomPowerShell has no BCD type, so a script packs the nibbles with -shl, -bor and -band. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no arithmetic.
CSSDoes not applyCSS has no arithmetic on encoded digits.
Regular expressionsDoes not applyA pattern can check that a hexadecimal string has only the digits 0 to 9 and a sign letter, but it does no arithmetic.
Language Verdict BCD support
Python idiom bytes.fromhex and hex on packed digits
JavaScript idiom bit operations on numbers
TypeScript idiom as JavaScript
Java idiom bit operations on byte and int
Kotlin idiom bit operations, as Java
C# idiom bit operations on byte and int
Go idiom bit operations on byte
Rust idiom bit operations on u8
C idiom bit operations on unsigned char
C++ idiom bit operations on std::uint8_t
Bash idiom printf with %x and arithmetic expansion
PowerShell idiom bit operations on [byte]
SQL absent no BCD type in the standard
Regex n/a a pattern can check digits in text but does no arithmetic
HTML n/a no arithmetic
CSS n/a no arithmetic

None of the core languages has a BCD type, so a program packs and unpacks the nibbles with shifts and masks. The data comes from outside the program: from a file of a mainframe system, from a database, or from a device. In COBOL, packed BCD is the data type COMPUTATIONAL-3, "an IBM extension adopted by many other compiler vendors", or PACKED-DECIMAL, "part of the 1985 COBOL standard"1, and PL/I has it as FIXED DECIMAL1.

PythonGitHub
def to_packed(n):
    digits = [int(d) for d in str(abs(n))] + [0xD if n < 0 else 0xC]
    if len(digits) % 2:
        digits.insert(0, 0)
    return bytes(digits[i] << 4 | digits[i + 1] for i in range(0, len(digits), 2))


def from_packed(b):
    nibbles = [x for byte in b for x in (byte >> 4, byte & 0x0F)]
    *digits, sign = nibbles
    if any(d > 9 for d in digits) or sign not in (0xC, 0xD, 0xF):
        raise ValueError("not packed BCD")
    value = int("".join(map(str, digits)))
    return -value if sign == 0xD else value


p = to_packed(-12345)
print("packed -12345:", p.hex(" ").upper())
print("back:", from_packed(p))
print("0x45 read as binary:", 0x45)
print("0x45 read as BCD:", (0x45 >> 4) * 10 + (0x45 & 0x0F))
try:
    from_packed(bytes.fromhex("1A3C"))
except ValueError as e:
    print("1A 3C:", e)
Output
packed -12345: 12 34 5D
back: -12345
0x45 read as binary: 69
0x45 read as BCD: 45
1A 3C: not packed BCD
  • Verdict: idiom. Python has no BCD type. The block packs two nibbles in each byte with shifts and masks, and bytes.hex shows the digits.
  • The decoder checks each digit nibble and the sign nibble, so the invalid nibble A raises an error.
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <optional>
#include <string>
#include <vector>

std::vector<std::uint8_t> to_packed(long long n) {
    std::string s = std::to_string(n < 0 ? -n : n);
    std::vector<std::uint8_t> nib;
    if (s.size() % 2 == 0) {
        nib.push_back(0);
    }
    for (char c : s) {
        nib.push_back(static_cast<std::uint8_t>(c - '0'));
    }
    nib.push_back(n < 0 ? 0xD : 0xC);
    std::vector<std::uint8_t> out;
    for (std::size_t i = 0; i < nib.size(); i += 2) {
        out.push_back(static_cast<std::uint8_t>(nib[i] << 4 | nib[i + 1]));
    }
    return out;
}

std::optional<long long> from_packed(const std::vector<std::uint8_t> &b) {
    long long v = 0;
    for (std::size_t i = 0; i < b.size(); ++i) {
        unsigned hi = b[i] >> 4;
        unsigned lo = b[i] & 0x0F;
        bool last = i + 1 == b.size();
        if (hi > 9 || (!last && lo > 9)) {
            return std::nullopt;
        }
        v = v * 10 + hi;
        if (!last) {
            v = v * 10 + lo;
        } else if (lo == 0xD) {
            v = -v;
        }
    }
    return v;
}

void print_hex(const char *label, const std::vector<std::uint8_t> &b) {
    std::cout << label << ':';
    for (auto x : b) {
        std::cout << ' ' << std::hex << std::uppercase << std::setw(2) << std::setfill('0')
                  << static_cast<unsigned>(x);
    }
    std::cout << std::dec << '\n';
}

int main() {
    auto p = to_packed(-12345);
    print_hex("packed -12345", p);
    std::cout << "back: " << from_packed(p).value() << '\n';
    print_hex("packed 2024", to_packed(2024));
    std::cout << "1A 3C valid: " << (from_packed({0x1A, 0x3C}) ? "yes" : "no") << '\n';
}
Output
packed -12345: 12 34 5D
back: -12345
packed 2024: 02 02 4C
1A 3C valid: no
  • Verdict: idiom. C++ has no BCD type. The block packs the nibbles into a std::vector<std::uint8_t>.
  • from_packed returns an empty std::optional for an invalid nibble.
JavaGitHub
import java.util.HexFormat;

public class Main {
  static byte[] toPacked(long n) {
    String s = Long.toString(Math.abs(n));
    int nibbles = s.length() + 1;
    int size = (nibbles + 1) / 2;
    byte[] out = new byte[size];
    int pos = size * 2 - 1;
    out[pos / 2] |= (byte) (n < 0 ? 0xD : 0xC);
    for (int i = s.length() - 1; i >= 0; i--) {
      pos--;
      int d = s.charAt(i) - '0';
      out[pos / 2] |= (byte) (pos % 2 == 0 ? d << 4 : d);
    }
    return out;
  }

  static long fromPacked(byte[] b) {
    long value = 0;
    for (int i = 0; i < b.length; i++) {
      int hi = (b[i] >> 4) & 0x0F;
      int lo = b[i] & 0x0F;
      if (hi > 9 || (i < b.length - 1 && lo > 9)) {
        throw new IllegalArgumentException("not packed BCD");
      }
      value = value * 10 + hi;
      if (i < b.length - 1) {
        value = value * 10 + lo;
      } else if (lo == 0xD) {
        value = -value;
      }
    }
    return value;
  }

  public static void main(String[] args) {
    HexFormat hex = HexFormat.ofDelimiter(" ").withUpperCase();
    byte[] p = toPacked(-12345);
    System.out.println("packed -12345: " + hex.formatHex(p));
    System.out.println("back: " + fromPacked(p));
    System.out.println("packed 2024: " + hex.formatHex(toPacked(2024)));
    try {
      fromPacked(new byte[] {0x1A, 0x3C});
    } catch (IllegalArgumentException e) {
      System.out.println("1A 3C: " + e.getMessage());
    }
  }
}
Output
packed -12345: 12 34 5D
back: -12345
packed 2024: 02 02 4C
1A 3C: not packed BCD
  • Verdict: idiom. Java has no BCD type. The block packs the digits from the right, so the sign nibble is last and a leading 0 nibble fills an even count of digits.
  • Java's byte is signed, so the decoder masks with 0x0F after the shift.
#include <stdio.h>

static unsigned bcd_add_byte(unsigned a, unsigned b, int *carry) {
    unsigned s = a + b;
    if ((s & 0x0Fu) > 9 || (a & 0x0Fu) + (b & 0x0Fu) > 0x0Fu) {
        s += 0x06;
    }
    if (s > 0x99) {
        s += 0x60;
    }
    *carry = s > 0xFF;
    return s & 0xFFu;
}

static unsigned to_bcd_byte(unsigned n) {
    return (n / 10) << 4 | (n % 10);
}

static unsigned from_bcd_byte(unsigned b) {
    return (b >> 4) * 10 + (b & 0x0Fu);
}

int main(void) {
    int carry = 0;
    unsigned seconds = to_bcd_byte(59);
    printf("59 as a BCD byte: 0x%02X\n", seconds);
    printf("0x%02X read as BCD: %u, as binary: %u\n", seconds, from_bcd_byte(seconds), seconds);
    unsigned r = bcd_add_byte(0x09, 0x08, &carry);
    printf("09 + 08: %02X carry %s\n", r, carry ? "yes" : "no");
    r = bcd_add_byte(0x99, 0x01, &carry);
    printf("99 + 01: %02X carry %s\n", r, carry ? "yes" : "no");
    printf("0x09 + 0x08 without the correction: %02X\n", 0x09 + 0x08);
    return 0;
}
Output
59 as a BCD byte: 0x59
0x59 read as BCD: 59, as binary: 89
09 + 08: 17 carry no
99 + 01: 00 carry yes
0x09 + 0x08 without the correction: 11
  • Verdict: idiom. C has no BCD type. The block converts one byte, as a driver does for the BCD time registers of a real-time clock, and adds two packed bytes with the add-6 correction.
  • The x86 DAA instruction does the correction in hardware, but it is not valid in 64-bit mode, so the code does it in C.
using System;

static byte[] ToPacked(long n)
{
    string s = Math.Abs(n).ToString();
    int size = (s.Length + 2) / 2;
    var digits = new int[size * 2];
    int start = size * 2 - 1 - s.Length;
    for (int i = 0; i < s.Length; i++)
    {
        digits[start + i] = s[i] - '0';
    }
    digits[size * 2 - 1] = n < 0 ? 0xD : 0xC;
    var output = new byte[size];
    for (int i = 0; i < size; i++)
    {
        output[i] = (byte)(digits[2 * i] << 4 | digits[2 * i + 1]);
    }
    return output;
}

static int BcdAddByte(int a, int b, out bool carry)
{
    int s = a + b;
    if ((s & 0x0F) > 9 || (a & 0x0F) + (b & 0x0F) > 0x0F)
    {
        s += 0x06;
    }
    if (s > 0x99)
    {
        s += 0x60;
    }
    carry = s > 0xFF;
    return s & 0xFF;
}

Console.WriteLine($"packed -12345: {Convert.ToHexString(ToPacked(-12345))}");
Console.WriteLine($"packed 127: {Convert.ToHexString(ToPacked(127))}");
int r = BcdAddByte(0x45, 0x38, out bool c);
Console.WriteLine($"45 + 38: {r:X2} carry {(c ? "yes" : "no")}");
r = BcdAddByte(0x99, 0x99, out c);
Console.WriteLine($"99 + 99: {r:X2} carry {(c ? "yes" : "no")}");
Output
packed -12345: 12345D
packed 127: 127C
45 + 38: 83 carry no
99 + 99: 98 carry yes
  • Verdict: idiom. C# has no BCD type. Convert.ToHexString shows the packed bytes, and each hexadecimal digit is one BCD digit or the sign.
  • BcdAddByte adds two packed bytes with the add-6 correction and returns the decimal carry, so 99 + 99 gives 98 and a carry for 198.
JavaScriptGitHub
function toPacked(n) {
  const digits = [...String(Math.abs(n))].map(Number);
  digits.push(n < 0 ? 0xd : 0xc);
  if (digits.length % 2) {
    digits.unshift(0);
  }
  const out = new Uint8Array(digits.length / 2);
  for (let i = 0; i < out.length; i++) {
    out[i] = (digits[2 * i] << 4) | digits[2 * i + 1];
  }
  return out;
}

function fromPacked(bytes) {
  let value = 0;
  for (let i = 0; i < bytes.length; i++) {
    const hi = bytes[i] >> 4;
    const lo = bytes[i] & 0x0f;
    if (hi > 9) {
      throw new RangeError("not packed BCD");
    }
    value = value * 10 + hi;
    if (i < bytes.length - 1) {
      if (lo > 9) {
        throw new RangeError("not packed BCD");
      }
      value = value * 10 + lo;
    } else if (lo === 0xd) {
      value = -value;
    }
  }
  return value;
}

const hex = (b) => [...b].map((x) => x.toString(16).toUpperCase().padStart(2, "0")).join(" ");
const p = toPacked(-12345);
console.log(`packed -12345: ${hex(p)}`);
console.log(`back: ${fromPacked(p)}`);
console.log(`0x09 + 0x08 in binary: ${(0x09 + 0x08).toString(16)}`);
try {
  fromPacked(Uint8Array.of(0x1a, 0x3c));
} catch (e) {
  console.log(`1A 3C: ${e.message}`);
}
Output
packed -12345: 12 34 5D
back: -12345
0x09 + 0x08 in binary: 11
1A 3C: not packed BCD
  • Verdict: idiom. JavaScript has no BCD type. The block packs the digits into a Uint8Array with shifts and masks.
  • A plain binary addition of two BCD bytes gives 0x11, not 17, so a BCD adder needs the add-6 correction.
package main

import (
	"errors"
	"fmt"
	"strconv"
)

func toPacked(n int64) []byte {
	sign := byte(0xC)
	if n < 0 {
		sign = 0xD
		n = -n
	}
	s := strconv.FormatInt(n, 10)
	nibbles := make([]byte, 0, len(s)+2)
	if len(s)%2 == 0 {
		nibbles = append(nibbles, 0)
	}
	for _, c := range s {
		nibbles = append(nibbles, byte(c-'0'))
	}
	nibbles = append(nibbles, sign)
	out := make([]byte, len(nibbles)/2)
	for i := range out {
		out[i] = nibbles[2*i]<<4 | nibbles[2*i+1]
	}
	return out
}

func fromPacked(b []byte) (int64, error) {
	var v int64
	for i, x := range b {
		hi, lo := x>>4, x&0x0F
		last := i == len(b)-1
		if hi > 9 || (!last && lo > 9) {
			return 0, errors.New("not packed BCD")
		}
		v = v*10 + int64(hi)
		if !last {
			v = v*10 + int64(lo)
		} else if lo == 0xD {
			v = -v
		}
	}
	return v, nil
}

func main() {
	p := toPacked(-12345)
	fmt.Printf("packed -12345: % X\n", p)
	v, _ := fromPacked(p)
	fmt.Println("back:", v)
	fmt.Printf("packed 2024: % X\n", toPacked(2024))
	_, err := fromPacked([]byte{0x1A, 0x3C})
	fmt.Println("1A 3C:", err)
}
Output
packed -12345: 12 34 5D
back: -12345
packed 2024: 02 02 4C
1A 3C: not packed BCD
  • Verdict: idiom. Go has no BCD type. The block builds a slice of nibbles, then joins each pair into a byte.
  • The % X verb prints the bytes in hexadecimal with spaces, which shows the decimal digits and the sign nibble.
RustGitHub
fn to_packed(n: i64) -> Vec<u8> {
    let mut nibbles: Vec<u8> = n.unsigned_abs().to_string().bytes().map(|c| c - b'0').collect();
    nibbles.push(if n < 0 { 0xD } else { 0xC });
    if nibbles.len() % 2 == 1 {
        nibbles.insert(0, 0);
    }
    nibbles.chunks(2).map(|p| p[0] << 4 | p[1]).collect()
}

fn from_packed(b: &[u8]) -> Option<i64> {
    let mut v: i64 = 0;
    for (i, &x) in b.iter().enumerate() {
        let (hi, lo) = (x >> 4, x & 0x0F);
        let last = i == b.len() - 1;
        if hi > 9 || (!last && lo > 9) {
            return None;
        }
        v = v * 10 + hi as i64;
        if !last {
            v = v * 10 + lo as i64;
        } else if lo == 0xD {
            v = -v;
        }
    }
    Some(v)
}

fn main() {
    let p = to_packed(-12345);
    let hex: Vec<String> = p.iter().map(|b| format!("{:02X}", b)).collect();
    println!("packed -12345: {}", hex.join(" "));
    println!("back: {:?}", from_packed(&p));
    println!("1A 3C: {:?}", from_packed(&[0x1A, 0x3C]));
    println!("0x45 as binary: {}, as BCD: {}", 0x45, (0x45 >> 4) * 10 + (0x45 & 0x0F));
}
Output
packed -12345: 12 34 5D
back: Some(-12345)
1A 3C: None
0x45 as binary: 69, as BCD: 45
  • Verdict: idiom. Rust has no BCD type. chunks(2) joins each pair of nibbles into a byte.
  • from_packed returns None for an invalid nibble, so the caller must handle bad data.
  • Other weights. Other codes use the bit weights 4221 and 74211, and there is excess-3, where each digit is stored as the digit plus 31.
  • Ten's complement. In place of a sign nibble, "Ten's complement representations for negative numbers offer an alternative approach to encoding the sign of packed (and other) BCD numbers."1
  • Densely packed decimal. Densely packed decimal stores three digits in ten bits, and it is used in one of the two decimal encodings of IEEE 754-20081.
  • Decimal floating point. Some calculators "employ a floating-point BCD format, typically with two or three digits for the (decimal) exponent"1. See Floating-point arithmetic.

Pitfalls

  • Hexadecimal is not decimal. A packed byte 0x45 means 45, but its binary value is 69. A program that reads a BCD field as a binary integer gets a wrong value with no error.
  • Invalid nibbles. The patterns A to F are not digits, except as a sign. A decoder must check each nibble, or bad data passes as a strange number.
  • Plain binary addition. 0x09 + 0x08 is 0x11 in binary, which reads as 11 in BCD. The result needs the add-6 correction.
  • A sign nibble in the wrong place. The sign is in the last nibble, and a value with an even number of digits needs a leading 0 nibble. Code that forgets this shifts every digit by one place.
  • x86-64. The DAA instruction "is not valid in 64-bit mode"2, so 64-bit code does the BCD correction in software.

Cost

Standard BCD "requires four bits per digit, roughly 20% more space than a binary encoding"1. "Practical existing implementations of BCD are typically slower than operations on binary representations, especially on embedded systems, due to limited processor support for native BCD operations."1 On the other hand, conversion to text "is a simple per-digit mapping, and can be done in linear (O(n)) time"1, and "Scaling by a power of 10 is simple."1 A decimal fraction such as 0.2 has a finite form in BCD but not in binary1.

History

"BCD was used in many early decimal computers, and is implemented in the instruction set of machines such as the IBM System/360 series and its descendants, Digital Equipment Corporation's VAX, the Burroughs B1700, and the Motorola 68000-series processors."1 "Packed BCD has been in use since at least the 1960s and is implemented in all IBM mainframe hardware since then."1 The Intel 8080, the Zilog Z80 and the x86 family have the DAA instruction1, and the BIOS of many personal computers stores the date and time in BCD because of the real-time clock chip of the IBM PC AT1. "In the 1972 case Gottschalk v. Benson, the U.S. Supreme Court overturned a lower court's decision that had allowed a patent for converting BCD-encoded numbers to binary on a computer."1

References

  1. Binary-coded decimal, Wikipedia, the introduction; Background; Packed BCD; Zoned decimal; Addition; Subtraction; BCD in computers; Comparison with pure binary; Application; Legal history
  2. DAA: Decimal Adjust AL after Addition, x86 instruction reference (from the Intel SDM), Description; Operation

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • at least three sources