259 → packed BCD

introfour bits per decimal digit

Answer

0000001001011001

Why this example is worth doing

Each decimal digit becomes its own four-bit group, so 259 is three nibbles rather than a single binary number. The page immediately contrasts it with the pure binary form of the same value, which is shorter, and states the trade plainly: BCD wastes space but converts to decimal display with no arithmetic at all. That is why it survives in instruments, calculators and anything with a seven-segment readout.

Try your own input in the BCD converter. Pack and unpack binary-coded decimal, and add with the +6 correction shown.

How the answer is reached

259 in packed BCD

Each decimal digit becomes its own 4-bit group with weights 8-4-2-1. The six patterns 1010..1111 are never produced.

259 in packed BCD — columns digit, 8421 code, placement
digit8421 codeplacement
20010high or low nibble of a byte
50101high or low nibble of a byte
91001high or low nibble of a byte

packed BCD0000 0010 0101 1001

compare with plain binary100000011BCD is longer: it trades density for digit-by-digit decimal arithmetic

Warning:

An odd digit count is left-padded with a zero nibble so the encoding fills whole bytes.

Compare with

Open this example in the BCD converter

The field arrives filled in with this example’s input.

Note:

Notation this page assumes

  • Bit strings are written most significant bit first, and bit 0 is the least significant bit.
  • A width is stated explicitly wherever it changes the answer; nothing is silently sign-extended or truncated.
  • Fractions are converted digit by digit and shown to a stated number of places rather than rounded silently.

Sources

  • Knuth, The Art of Computer Programming, Vol. 2, §4.1 “Positional Number Systems” (1997)
  • ANSI X3.4 / ISO-IEC 646, the ASCII character set