Hubbry Logo
Binary-coded decimalBinary-coded decimalMain
Open search
Binary-coded decimal
Community hub
Binary-coded decimal
logo
8 pages, 0 posts
0 subscribers
Be the first to start a discussion here.
Be the first to start a discussion here.
Binary-coded decimal
Binary-coded decimal
from Wikipedia

A binary clock might use LEDs to express binary values. In this clock, each column of LEDs shows a binary-coded decimal numeral of the traditional sexagesimal time.

In computing and electronic systems, 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. Sometimes, special bit patterns are used for a sign or other indications (e.g. error or overflow).

In byte-oriented systems (i.e. most modern computers), the term unpacked BCD[1] usually implies a full byte for each digit (often including a sign), whereas packed BCD typically encodes two digits within a single byte by taking advantage of the fact that four bits are enough to represent the range 0 to 9. The precise four-bit encoding, however, may vary for technical reasons (e.g. Excess-3).

The ten states representing a BCD digit are sometimes called tetrades[2][3] (the nibble typically needed to hold them is also known as a tetrade) while the unused, don't care-states are named pseudo-tetrad(e)s[de],[4][5][6][7][8] pseudo-decimals,[3] or pseudo-decimal digits.[9][10][nb 1]

BCD's main virtue, in comparison to binary positional systems, is its more accurate representation and rounding of decimal quantities, as well as its ease of conversion into conventional human-readable representations. Its principal drawbacks are a slight increase in the complexity of the circuits needed to implement basic arithmetic as well as slightly less dense storage.

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.

BCD per se is not as widely used as in the past, and is unavailable or limited in newer instruction sets (e.g., ARM; x86 in long mode). However, decimal fixed-point and decimal floating-point formats are still important and continue to be used in financial, commercial, and industrial computing, where the subtle conversion and fractional rounding errors that are inherent in binary floating point formats cannot be tolerated.[11]

Background

[edit]

BCD takes advantage of the fact that any one decimal numeral can be represented by a four-bit pattern. An obvious way of encoding digits is Natural BCD (NBCD), where each decimal digit is represented by its corresponding four-bit binary value, as shown in the following table. This is also called "8421" encoding.

Decimal digit BCD
8 4 2 1
0 0 0 0 0
1 0 0 0 1
2 0 0 1 0
3 0 0 1 1
4 0 1 0 0
5 0 1 0 1
6 0 1 1 0
7 0 1 1 1
8 1 0 0 0
9 1 0 0 1

This scheme can also be referred to as Simple Binary-Coded Decimal (SBCD) or BCD 8421, and is the most common encoding.[12] Others include the so-called "4221" and "7421" encoding – named after the weighting used for the bits – and "Excess-3".[13] For example, the BCD digit 6, 0110'b in 8421 notation, is 1100'b in 4221 (two encodings are possible), 0110'b in 7421, while in Excess-3 it is 1001'b ().

4-bit BCD codes and pseudo-tetrades
Bit Weight  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15         Comment        
4 8 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 Binary
3 4 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
2 2 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
Name 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Decimal
8 4 2 1 (XS-0) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [14][15][16][17][nb 2]
7 4 2 1 0 1 2 3 4 5 6   7 8 9           [18][19][20]
Aiken (2 4 2 1) 0 1 2 3 4             5 6 7 8 9 [14][15][16][17][nb 3]
Excess-3 (XS-3) -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 11 12 [14][15][16][17][nb 2]
Excess-6 (XS-6) -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 [18][nb 2]
Jump-at-2 (2 4 2 1) 0 1             2 3 4 5 6 7 8 9 [16][17]
Jump-at-8 (2 4 2 1) 0 1 2 3 4 5 6 7             8 9 [21][22][16][17][nb 4]
4 2 2 1 (I) 0 1 2 3     4 5         6 7 8 9 [16][17]
4 2 2 1 (II) 0 1 2 3     4 5     6 7     8 9 [21][22]
5 4 2 1 0 1 2 3 4       5 6 7 8 9       [18][14][16][17]
5 2 2 1 0 1 2 3     4   5 6 7 8     9   [14][16][17]
5 1 2 1 0 1 2 3       4 5 6 7 8       9 [19]
5 3 1 1 0 1   2 3 4     5 6   7 8 9     [16][17]
White (5 2 1 1) 0 1   2   3   4 5 6   7   8   9 [23][18][14][16][17]
5 2 1 1 0 1   2   3   4 5   6   7   8 9 [24]
  0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Magnetic tape   1 2 3 4 5 6 7 8 9 0           [15]
Paul   1 3 2 6 7 5 4   0     8 9     [25]
Gray 0 1 3 2 6 7 5 4 15 14 12 13 8 9 11 10 [26][14][15][16][17][nb 2]
Glixon 0 1 3 2 6 7 5 4 9       8       [27][14][15][16][17]
Ledley 0 1 3 2 7 6 4 5         8   9   [28]
4 3 1 1 0 1   2 3     5 4     6 7   8 9 [19]
LARC 0 1   2     4 3 5 6   7     9 8 [29]
Klar 0 1   2     4 3 9 8   7     5 6 [2][3]
Petherick (RAE)   1 3 2   0 4     8 6 7   9 5   [30][31][nb 5]
O'Brien I (Watts) 0 1 3 2     4   9 8 6 7     5   [32][14][16][17][nb 6]
5-cyclic 0 1 3 2     4   5 6 8 7     9   [28]
Tompkins I 0 1 3 2     4     9     8 7 5 6 [33][14][16][17]
Lippel 0 1 2 3     4     9     8 7 6 5 [34][35][14]
O'Brien II   0 2 1 4   3     9 7 8 5   6   [32][14][16][17]
Tompkins II     0 1 4 3   2   7 9 8 5 6     [33][14][16][17]
Excess-3 Gray -3 -2 0 -1 4 3 1 2 12 11 9 10 5 6 8 7 [16][17][20][nb 7][nb 2]
6 3 −2 −1 (I)         3 2 1 0   5 4 8 9   7 6 [29][36]
6 3 −2 −1 (II) 0       3 2 1   6 5 4   9 8 7   [29][36]
8 4 −2 −1 0       4 3 2 1 8 7 6 5       9 [29]
Lucal 0 15 14 1 12 3 2 13 8 7 6 9 4 11 10 5 [37]
Kautz I 0     2   5 1 3   7 9   8 6   4 [18]
Kautz II   9 4   1   3 2 8   6 7   0 5   [18][14]
Susskind I   0   1   4 3 2   9   8 5   6 7 [35]
Susskind II   0   1   9   8 4   3 2 5   6 7 [35]
  0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

The following table represents decimal digits from 0 to 9 in various BCD encoding systems. In the headers, the "8421" indicates the weight of each bit. In the fifth column ("BCD 84−2−1"), two of the weights are negative. Both ASCII and EBCDIC character codes for the digits, which are examples of zoned BCD, are also shown.

 
Digit
BCD
8421
Stibitz code or Excess-3 Aiken-Code or BCD
2421
BCD
84−2−1
IBM 702, IBM 705, IBM 7080, IBM 1401
8421
ASCII
0000 8421
EBCDIC
0000 8421
0 0000 0011 0000 0000 1010 0011 0000 1111 0000
1 0001 0100 0001 0111 0001 0011 0001 1111 0001
2 0010 0101 0010 0110 0010 0011 0010 1111 0010
3 0011 0110 0011 0101 0011 0011 0011 1111 0011
4 0100 0111 0100 0100 0100 0011 0100 1111 0100
5 0101 1000 1011 1011 0101 0011 0101 1111 0101
6 0110 1001 1100 1010 0110 0011 0110 1111 0110
7 0111 1010 1101 1001 0111 0011 0111 1111 0111
8 1000 1011 1110 1000 1000 0011 1000 1111 1000
9 1001 1100 1111 1111 1001 0011 1001 1111 1001

As most computers deal with data in 8-bit bytes, it is possible to use one of the following methods to encode a BCD number:

  • Unpacked: Each decimal digit is encoded into one byte, with four bits representing the number and the remaining bits having no significance.
  • Packed: Two decimal digits are encoded into a single byte, with one digit in the least significant nibble (bits 0 through 3) and the other numeral in the most significant nibble (bits 4 through 7).[nb 8]

As an example, encoding the decimal number 91 using unpacked BCD results in the following binary pattern of two bytes:

Decimal:         9         1
Binary : 0000 1001 0000 0001

In packed BCD, the same number would fit into a single byte:

Decimal:    9    1
Binary : 1001 0001

Hence the numerical range for one unpacked BCD byte is zero through nine inclusive, whereas the range for one packed BCD byte is zero through ninety-nine inclusive.

To represent numbers larger than the range of a single byte any number of contiguous bytes may be used. For example, to represent the decimal number 12345 in packed BCD, using big-endian format, a program would encode as follows:

Decimal:    0    1    2    3    4    5
Binary : 0000 0001 0010 0011 0100 0101

Here, the most significant nibble of the most significant byte has been encoded as zero, so the number is stored as 012345 (but formatting routines might replace or remove leading zeros). Packed BCD is more efficient in storage usage than unpacked BCD; encoding the same number (with the leading zero) in unpacked format would consume twice the storage.

Shifting and masking operations are used to pack or unpack a packed BCD digit. Other bitwise operations are used to convert a numeral to its equivalent bit pattern or reverse the process.

Packed BCD

[edit]

Some computers whose words are multiples of an octet (8-bit byte), for example contemporary IBM mainframe systems, support packed BCD (or packed decimal[38]) numeric representations, in which each nibble represents either a decimal digit or a sign.[nb 8] Packed BCD has been in use since at least the 1960s and is implemented in all IBM mainframe hardware since then. Most implementations are big endian, i.e. with the more significant digit in the upper half of each byte, and with the leftmost byte (residing at the lowest memory address) containing the most significant digits of the packed decimal value. The lower nibble of the rightmost byte is usually used as the sign flag, although some unsigned representations lack a sign flag.

As an example, a 4-byte value consists of 8 nibbles, wherein the upper 7 nibbles store the digits of a 7-digit decimal value, and the lowest nibble indicates the sign of the decimal integer value. Standard sign values are 1100 (hex C) for positive (+) and 1101 (D) for negative (−). This convention comes from the zone field for EBCDIC characters and the signed overpunch representation.

Other allowed signs are 1010 (A) and 1110 (E) for positive and 1011 (B) for negative. IBM System/360 processors will use the 1010 (A) and 1011 (B) signs if the A bit is set in the PSW, for the ASCII-8 standard that never passed. Most implementations also provide unsigned BCD values with a sign nibble of 1111 (F).[39][40][41] ILE RPG uses 1111 (F) for positive and 1101 (D) for negative.[42] These match the EBCDIC zone for digits without a sign overpunch. In packed BCD, the number 127 is represented by 0001 0010 0111 1100 (127C) and −127 is represented by 0001 0010 0111 1101 (127D). Burroughs systems used 1101 (D) for negative, and any other value is considered a positive sign value (the processors will normalize a positive sign to 1100 (C)).

Sign
digit
BCD
8 4 2 1
Sign Notes
A 1 0 1 0 +  
B 1 0 1 1  
C 1 1 0 0 + Preferred
D 1 1 0 1 Preferred
E 1 1 1 0 +  
F 1 1 1 1 + Unsigned

No matter how many bytes wide a word is, there is always an even number of nibbles because each byte has two of them. Therefore, a word of n bytes can contain up to (2n)−1 decimal digits, which is always an odd number of digits. A decimal number with d digits requires 1/2(d+1) bytes of storage space.

For example, a 4-byte (32-bit) word can hold seven decimal digits plus a sign and can represent values ranging from ±9,999,999. Thus the number −1,234,567 is 7 digits wide and is encoded as:

0001 0010 0011 0100 0101 0110 0111 1101
1    2    3    4    5    6    7    −

Like character strings, the first byte of the packed decimal – that with the most significant two digits – is usually stored in the lowest address in memory, independent of the endianness of the machine.

In contrast, a 4-byte binary two's complement integer can represent values from −2,147,483,648 to +2,147,483,647.

While packed BCD does not make optimal use of storage (using about 20% more memory than binary notation to store the same numbers), conversion to ASCII, EBCDIC, or the various encodings of Unicode is made trivial, as no arithmetic operations are required. The extra storage requirements are usually offset by the need for the accuracy and compatibility with calculator or hand calculation that fixed-point decimal arithmetic provides. Denser packings of BCD exist which avoid the storage penalty and also need no arithmetic operations for common conversions.

Packed BCD is supported in the COBOL programming language as the "COMPUTATIONAL-3" (an IBM extension adopted by many other compiler vendors) or "PACKED-DECIMAL" (part of the 1985 COBOL standard) data type. It is supported in PL/I as "FIXED DECIMAL". Beside the IBM System/360 and later compatible mainframes, packed BCD is implemented in the native instruction set of the original VAX processors from Digital Equipment Corporation and some models of the SDS Sigma series mainframes, and is the native format for the Burroughs Medium Systems line of mainframes (descended from the 1950s Electrodata 200 series).

Ten's complement representations for negative numbers offer an alternative approach to encoding the sign of packed (and other) BCD numbers. In this case, positive numbers always have a most significant digit between 0 and 4 (inclusive), while negative numbers are represented by the 10's complement of the corresponding positive number.

As a result, this system allows for 32-bit packed BCD numbers to range from −50,000,000 to +49,999,999, and −1 is represented as 99999999. (As with two's complement binary numbers, the range is not symmetric about zero.)

Fixed-point packed decimal

[edit]

Fixed-point decimal numbers are supported by some programming languages (such as COBOL and PL/I). These languages allow the programmer to specify an implicit decimal point in front of one of the digits.

For example, a packed decimal value encoded with the bytes 12 34 56 7C represents the fixed-point value +1,234.567 when the implied decimal point is located between the fourth and fifth digits:

12 34 56 7C
12 34.56 7+

The decimal point is not actually stored in memory, as the packed BCD storage format does not provide for it. Its location is simply known to the compiler, and the generated code acts accordingly for the various arithmetic operations.

Higher-density encodings

[edit]

If a decimal digit requires four bits, then three decimal digits require 12 bits. However, since 210 (1,024) is greater than 103 (1,000), if three decimal digits are encoded together, only 10 bits are needed. Two such encodings are Chen–Ho encoding and densely packed decimal (DPD). The latter has the advantage that subsets of the encoding encode two digits in the optimal seven bits and one digit in four bits, as in regular BCD.

Zoned decimal

[edit]

Some implementations, for example IBM mainframe systems, support zoned decimal numeric representations. Each decimal digit is stored in one 8-bit[nb 9] byte, with the lower four bits encoding the digit in BCD form. The upper four[nb 10] bits, called the "zone" bits, are usually set to a fixed value so that the byte holds a character value corresponding to the digit, or to values representing plus or minus. EBCDIC[nb 11] systems use a zone value of 11112 (F16), yielding F016-F916, the codes for "0" through "9", a zone value of 11002 (C16) for positive, yielding C016-C916, the codes for "{" through "I" and a zone value of 11102 (D16) for negative, yielding D016-D916, the codes for the characters "}" through "R". Similarly, ASCII systems use a zone value of 0011 (hex 3), giving character codes 30 to 39 (hex).

For signed zoned decimal values, the rightmost (least significant) zone nibble holds the sign digit, which is the same set of values that are used for signed packed decimal numbers (see above). Thus a zoned decimal value encoded as the hex bytes F1 F2 D3 represents the signed decimal value −123:

F1 F2 D3
1  2 −3

EBCDIC zoned decimal conversion table

[edit]
BCD digit Hexadecimal EBCDIC character
0+ C0 A0 E0 F0 { (*)   \ (*) 0
1+ C1 A1 E1 F1 A ~ (*)   1
2+ C2 A2 E2 F2 B s S 2
3+ C3 A3 E3 F3 C t T 3
4+ C4 A4 E4 F4 D u U 4
5+ C5 A5 E5 F5 E v V 5
6+ C6 A6 E6 F6 F w W 6
7+ C7 A7 E7 F7 G x X 7
8+ C8 A8 E8 F8 H y Y 8
9+ C9 A9 E9 F9 I z Z 9
0− D0 B0     }  (*) ^  (*)    
1− D1 B1     J      
2− D2 B2     K      
3− D3 B3     L      
4− D4 B4     M      
5− D5 B5     N      
6− D6 B6     O      
7− D7 B7     P      
8− D8 B8     Q      
9− D9 B9     R      

(*) Note: These characters vary depending on the local character code page setting.

Fixed-point zoned decimal

[edit]

Some languages (such as COBOL and PL/I) directly support fixed-point zoned decimal values, assigning an implicit decimal point at some location between the decimal digits of a number.

For example, given a six-byte signed zoned decimal value with an implied decimal point to the right of the fourth digit, the hex bytes F1 F2 F7 F9 F5 C0 represent the value +1,279.50:

F1 F2 F7 F9 F5 C0
1  2  7  9. 5 +0

Operations with BCD

[edit]

Addition

[edit]

It is possible to perform addition by first adding in binary, and then converting to BCD afterwards. 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. The reason for adding 6 is that there are 16 possible 4-bit BCD values (since 24 = 16), but only 10 values are valid (0000 through 1001). For example:

1001 + 1000 = 10001
   9 +    8 =    17

10001 is the binary, not decimal, representation of the desired result, but the most significant 1 (the "carry") cannot fit in a 4-bit binary number. In BCD as in decimal, there cannot exist a value greater than 9 (1001) per digit. To correct this, 6 (0110) is added to the total, and then the result is treated as two nibbles:

10001 + 0110 = 00010111 => 0001 0111
   17 +    6 =       23       1    7

The two nibbles of the result, 0001 and 0111, correspond to the digits "1" and "7". This yields "17" in BCD, which is the correct result.

This technique can be extended to adding multiple digits by adding in groups from right to left, propagating the second digit as a carry, always comparing the 5-bit result of each digit-pair sum to 9. Some CPUs provide a half-carry flag to facilitate BCD arithmetic adjustments following binary addition and subtraction operations. The Intel 8080, the Zilog Z80 and the CPUs of the x86 family provide the opcode DAA (Decimal Adjust Accumulator).

Subtraction

[edit]

Subtraction is done by adding the ten's complement of the subtrahend to the minuend. To represent the sign of a number in BCD, the number 0000 is used to represent a positive number, and 1001 is used to represent a negative number. The remaining 14 combinations are invalid signs. To illustrate signed BCD subtraction, consider the following problem: 357 − 432.

In signed BCD, 357 is 0000 0011 0101 0111. The ten's complement of 432 can be obtained by taking the nine's complement of 432, and then adding one. So, 999 − 432 = 567, and 567 + 1 = 568. By preceding 568 in BCD by the negative sign code, the number −432 can be represented. So, −432 in signed BCD is 1001 0101 0110 1000.

Now that both numbers are represented in signed BCD, they can be added together:

  0000 0011 0101 0111
  0    3    5    7
+ 1001 0101 0110 1000
  9    5    6    8
= 1001 1000 1011 1111
  9    8    11   15

Since BCD is a form of decimal representation, several of the digit sums above are invalid. In the event that an invalid entry (any BCD digit greater than 1001) exists, 6 is added to generate a carry bit and cause the sum to become a valid entry. So, adding 6 to the invalid entries results in the following:

  1001 1000 1011 1111
  9    8    11   15
+ 0000 0000 0110 0110
  0    0    6    6
= 1001 1001 0010 0101
  9    9    2    5

Thus the result of the subtraction is 1001 1001 0010 0101 (−925). To confirm the result, note that the first digit is 9, which means negative. This seems to be correct since 357 − 432 should result in a negative number. The remaining nibbles are BCD, so 1001 0010 0101 is 925. The ten's complement of 925 is 1000 − 925 = 75, so the calculated answer is −75.

If there are a different number of nibbles being added together (such as 1053 − 2), the number with the fewer digits must first be prefixed with zeros before taking the ten's complement or subtracting. So, with 1053 − 2, 2 would have to first be represented as 0002 in BCD, and the ten's complement of 0002 would have to be calculated.

BCD in computers

[edit]

IBM

[edit]

IBM used the terms Binary-Coded Decimal Interchange Code (BCDIC, sometimes just called BCD), for 6-bit alphanumeric codes that represented numbers, upper-case letters and special characters. Some variation of BCDIC alphamerics is used in most early IBM computers, including the IBM 1620 (introduced in 1959), IBM 1400 series, and non-decimal architecture members of the IBM 700/7000 series.

The IBM 1400 series are character-addressable machines, each location being six bits labeled B, A, 8, 4, 2 and 1, plus an odd parity check bit (C) and a word mark bit (M). For encoding digits 1 through 9, B and A are zero and the digit value represented by standard 4-bit BCD in bits 8 through 1. For most other characters bits B and A are derived simply from the "12", "11", and "0" "zone punches" in the punched card character code, and bits 8 through 1 from the 1 through 9 punches. A "12 zone" punch set both B and A, an "11 zone" set B, and a "0 zone" (a 0 punch combined with any others) set A. Thus the letter A, which is (12,1) in the punched card format, is encoded (B,A,1). The currency symbol $, (11,8,3) in the punched card, was encoded in memory as (B,8,2,1). This allows the circuitry to convert between the punched card format and the internal storage format to be very simple with only a few special cases. One important special case is digit 0, represented by a lone 0 punch in the card, and (8,2) in core memory.[43]

The memory of the IBM 1620 is organized into 6-bit addressable digits, the usual 8, 4, 2, 1 plus F, used as a flag bit and C, an odd parity check bit. BCD alphamerics are encoded using digit pairs, with the "zone" in the even-addressed digit and the "digit" in the odd-addressed digit, the "zone" being related to the 12, 11, and 0 "zone punches" as in the 1400 series. Input/output translation hardware converted between the internal digit pairs and the external standard 6-bit BCD codes.

In the decimal architecture IBM 7070, IBM 7072, and IBM 7074 alphamerics are encoded using digit pairs (using two-out-of-five code in the digits, not BCD) of the 10-digit word, with the "zone" in the left digit and the "digit" in the right digit. Input/output translation hardware converted between the internal digit pairs and the external standard 6-bit BCD codes.

With the introduction of System/360, IBM expanded 6-bit BCD alphamerics to 8-bit EBCDIC, allowing the addition of many more characters (e.g., lowercase letters). A variable length packed BCD numeric data type is also implemented, providing machine instructions that perform arithmetic directly on packed decimal data.

On the IBM 1130 and 1800, packed BCD is supported in software by IBM's Commercial Subroutine Package.

Today, BCD data is still heavily used in IBM databases such as IBM Db2 and processors such as z/Architecture and POWER6 and later Power ISA processors. In these products, the BCD is usually zoned BCD (as in EBCDIC or ASCII), packed BCD (two decimal digits per byte), or "pure" BCD encoding (one decimal digit stored as BCD in the low four bits of each byte). All of these are used within hardware registers and processing units, and in software.

Other computers

[edit]

The Digital Equipment Corporation VAX series includes instructions that can perform arithmetic directly on packed BCD data and convert between packed BCD data and other integer representations.[41] The VAX's packed BCD format is compatible with that on IBM System/360 and IBM's later compatible processors. The MicroVAX and later VAX implementations dropped this ability from the CPU but retained code compatibility with earlier machines by implementing the missing instructions in an operating system-supplied software library. This is invoked automatically via exception handling when the defunct instructions are encountered, so that programs using them can execute without modification on the newer machines.

Many processors have hardware support for BCD-encoded integer arithmetic. For example, the 6502,[44][45] the Motorola 68000 series,[46] and the x86 series.[47] The Intel x86 architecture supports a unique 18-digit (ten-byte) BCD format that can be loaded into and stored from the floating point registers, from where computations can be performed.[48]

In more recent computers such capabilities are almost always implemented in software rather than the CPU's instruction set, but BCD numeric data are still extremely common in commercial and financial applications.

There are tricks for implementing packed BCD and zoned decimal add–or–subtract operations using short but difficult to understand sequences of word-parallel logic and binary arithmetic operations.[49] For example, the following code (written in C) computes an unsigned 8-digit packed BCD addition using 32-bit binary operations:

uint32_t BCDadd(uint32_t a, uint32_t b)
{
    uint32_t t1, t2;    // unsigned 32-bit intermediate values

    t1 = a + 0x06666666;
    t2 = t1 ^ b;                   // sum without carry propagation
    t1 = t1 + b;                   // provisional sum
    t2 = t1 ^ t2;                  // all the binary carry bits
    t2 = ~t2 & 0x11111110;         // just the BCD carry bits
    t2 = (t2 >> 2) | (t2 >> 3);    // correction
    return t1 - t2;                // corrected BCD sum
}

BCD in electronics

[edit]

BCD is common in electronic systems where a numeric value is to be displayed, especially in systems consisting solely of digital logic, and not containing a microprocessor. By employing BCD, the manipulation of numerical data for display can be greatly simplified by treating each digit as a separate single sub-circuit.

This matches much more closely the physical reality of display hardware—a designer might choose to use a series of separate identical seven-segment displays to build a metering circuit, for example. If the numeric quantity were stored and manipulated as pure binary, interfacing with such a display would require complex circuitry. Therefore, in cases where the calculations are relatively simple, working throughout with BCD can lead to an overall simpler system than converting to and from binary. Most pocket calculators do all their calculations in BCD.

The same argument applies when hardware of this type uses an embedded microcontroller or other small processor. Often, representing numbers internally in BCD format results in smaller code, since a conversion from or to binary representation can be expensive on such limited processors. For these applications, some small processors feature dedicated arithmetic modes, which assist when writing routines that manipulate BCD quantities.[50][51]

Comparison with pure binary

[edit]

Advantages

[edit]
  • Scaling by a power of 10 is simple.
  • Rounding at a decimal digit boundary is simpler. Addition and subtraction in decimal do not require rounding.[dubiousdiscuss]
  • The alignment of two decimal numbers (for example 1.3 + 27.08) is a simple, exact shift.
  • Conversion to a character form or for display (e.g., to a text-based format such as XML, or to drive signals for a seven-segment display) is a simple per-digit mapping, and can be done in linear (O(n)) time. Conversion from pure binary involves relatively complex logic that spans digits, and for large numbers, no linear-time conversion algorithm is known (see Binary number § Conversion to and from other numeral systems).
  • Many non-integral values, such as decimal 0.2, have an infinite place-value representation in binary (.001100110011...) but have a finite place-value in binary-coded decimal (0.0010). Consequently, a system based on binary-coded decimal representations of decimal fractions avoids errors representing and calculating such values. This is useful in financial calculations.

Disadvantages

[edit]
  • 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.[52]
  • Some operations are more complex to implement. Adders require extra logic to cause them to wrap and generate a carry early. Also, 15 to 20% more circuitry is needed for BCD add compared to pure binary.[citation needed] Multiplication requires the use of algorithms that are somewhat more complex than shift-mask-add (a binary multiplication, requiring binary shifts and adds or the equivalent, per-digit or group of digits is required).
  • Standard BCD requires four bits per digit, roughly 20% more space than a binary encoding (the ratio of 4 bits to log210 bits is 1.204). When packed so that three digits are encoded in ten bits, the storage overhead is greatly reduced, at the expense of an encoding that is unaligned with the 8-bit byte boundaries common on existing hardware, resulting in slower implementations on these systems.

Representational variations

[edit]

Various BCD implementations exist that employ other representations for numbers. Programmable calculators manufactured by Texas Instruments, Hewlett-Packard, and others typically employ a floating-point BCD format, typically with two or three digits for the (decimal) exponent. The extra bits of the sign digit may be used to indicate special numeric values, such as infinity, underflow/overflow, and error (a blinking display).

Signed variations

[edit]

Signed decimal values may be represented in several ways. The COBOL programming language, for example, supports five zoned decimal formats, with each one encoding the numeric sign in a different way:

Type Description Example
Unsigned No sign nibble F1 F2 F3
Signed trailing (canonical format) Sign nibble in the last (least significant) byte F1 F2 C3
Signed leading (overpunch) Sign nibble in the first (most significant) byte C1 F2 F3
Signed trailing separate Separate sign character byte ('+' or '−') following the digit bytes F1 F2 F3 2B
Signed leading separate Separate sign character byte ('+' or '−') preceding the digit bytes 2B F1 F2 F3

Telephony binary-coded decimal (TBCD)

[edit]

3GPP developed TBCD,[53] an expansion to BCD where the remaining (unused) bit combinations are used to add specific telephony symbols,[54][55] similar to those in telephone keypad design.

Decimal
digit
TBCD
8 4 2 1
* 1 0 1 0
# 1 0 1 1
a 1 1 0 0
b 1 1 0 1
c 1 1 1 0
Used as filler when there is an odd number of digits 1 1 1 1

The mentioned 3GPP document defines TBCD-STRING with swapped nibbles in each byte. Bits, octets and digits indexed from 1, bits from the right, digits and octets from the left.

bits 8765 of octet n encoding digit 2n

bits 4321 of octet n encoding digit 2(n – 1) + 1

Meaning number 1234, would become 21 43 in TBCD.

This format is used in modern mobile telephony to send dialed numbers, as well as operator ID (the MCC/MNC tuple), IMEI, IMSI (SUPI), et.c.[56][57]

Alternative encodings

[edit]

If errors in representation and computation are more important than the speed of conversion to and from display, a scaled binary representation may be used, which stores a decimal number as a binary-encoded integer and a binary-encoded signed decimal exponent. For example, 0.2 can be represented as 2×10−1.

This representation allows rapid multiplication and division, but may require shifting by a power of 10 during addition and subtraction to align the decimal points. It is appropriate for applications with a fixed number of decimal places that do not then require this adjustment—particularly financial applications where 2 or 4 digits after the decimal point are usually enough. Indeed, this is almost a form of fixed point arithmetic since the position of the radix point is implied.

The Hertz and Chen–Ho encodings provide Boolean transformations for converting groups of three BCD-encoded digits to and from 10-bit values[nb 1] that can be efficiently encoded in hardware with only 2 or 3 gate delays. Densely packed decimal (DPD) is a similar scheme[nb 1] that is used for most of the significand, except the lead digit, for one of the two alternative decimal encodings specified in the IEEE 754-2008 floating-point standard.

Application

[edit]

The BIOS in many personal computers stores the date and time in BCD because the MC6818 real-time clock chip used in the original IBM PC AT motherboard provided the time encoded in BCD. This form is easily converted into ASCII for display.[58][59]

The Atari 8-bit computers use a BCD format for floating point numbers. The MOS Technology 6502 processor has a BCD mode for the addition and subtraction instructions. The Psion Organiser 1 handheld computer's manufacturer-supplied software also uses BCD to implement floating point; later Psion models use binary exclusively.

Early models of the PlayStation 3 store the date and time in BCD. This led to a worldwide outage of the console on 1 March 2010. The last two digits of the year stored as BCD were misinterpreted as 16 causing an error in the unit's date, rendering most functions inoperable. This has been referred to as the Year 2010 problem.

[edit]

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.

The decision noted that a patent "would wholly pre-empt the mathematical formula and in practical effect would be a patent on the algorithm itself".[60] This was a landmark judgement that determined the patentability of software and algorithms.

See also

[edit]

Notes

[edit]

References

[edit]

Further reading

[edit]
[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
Binary-coded decimal (BCD) is a method of encoding decimal numbers in , where each individual digit from 0 to 9 is represented by a fixed group of four binary bits corresponding to its pure binary value. Developed in the early era of to reconcile the binary nature of digital hardware with the familiar to humans, BCD emerged as a hybrid representation that preserves structure while using binary digits for storage and processing. This approach was particularly prevalent in mid-20th-century mainframe s, where it facilitated direct arithmetic without the need for complex conversions that could introduce errors in binary-only representations. Key variants include packed BCD, which stores two digits per byte for efficiency, and zoned BCD, often used in character encodings like for compatibility with text processing. One primary advantage of BCD is its simplicity in converting between and binary formats, making it ideal for applications requiring human-readable outputs, such as digital displays and calculators, where each digit can be directly mapped without algorithmic transformation. Additionally, BCD arithmetic avoids the discrepancies common in pure binary floating-point operations, ensuring exact representation of fractions in fields like and scientific computation. However, BCD is less storage-efficient than pure binary, as it utilizes only 10 of the 16 possible 4-bit combinations per digit, leading to up to 20% more space for the same numerical range and potentially slower processing due to specialized hardware or software handling. Despite these drawbacks, BCD persists in modern embedded systems, real-time clocks, programmable logic controllers (PLCs), and legacy-compatible environments where decimal precision outweighs efficiency concerns.

Fundamentals

Definition and Principles

Binary-coded decimal (BCD) is a method of encoding numbers in by representing each individual digit with a fixed group of bits, typically four bits to accommodate the digits 0 through 9. This approach allows computers and digital systems to store and process data directly in a form that mirrors the structure, eliminating the need for repeated binary-to-decimal conversions during arithmetic operations. In the standard BCD scheme, known as the 8421 weighted code, each decimal digit is encoded using four binary bits where the weights correspond to powers of 2 (8, 4, 2, 1). The encodings are as follows: 0000 for 0, 0001 for 1, 0010 for 2, 0011 for 3, 0100 for 4, 0101 for 5, 0110 for 6, 0111 for 7, 1000 for 8, and 1001 for 9, with the remaining combinations (1010 through 1111) left unused to ensure unambiguous . This fixed-width encoding preserves the positional significance of each decimal digit, preventing issues like carry propagation from altering higher digits in ways that deviate from decimal arithmetic rules. A key principle of BCD is its ability to maintain exact values without the rounding or approximation errors inherent in binary representations of non-integer decimals, as each digit is handled independently and no fractional binary expansions are required. For instance, the number 29 is encoded in BCD as 0010 1001 (equivalent to 0x29), where the first (0010) represents 2 and the second (1001) represents 9. In terms of storage, BCD is less efficient than pure binary for the same numerical range; for example, decimal 99 requires 8 bits in BCD (1001 1001) but only 7 bits in binary (1100011). This trade-off prioritizes decimal fidelity over compactness, making BCD suitable for applications where precise decimal handling is essential.

Historical Background

Binary-coded decimal (BCD) emerged in the context of early computing's need for to align with human intuition and existing equipment. In the , electromechanical machines like the utilized decimal mechanisms, such as wheels with ten positions for digits, to ensure outputs were directly readable and compatible with punch card tabulators, prioritizing usability over the emerging binary logic in electronic designs. During the 1950s, advanced BCD as a method to encode individual decimal digits using binary bits, facilitating the transition to electronic computers while preserving decimal accuracy for applications. This development was integral to punch card systems and early machines like the (introduced in 1959), which employed 6-bit BCD variants to represent numeric data efficiently in binary hardware. Standardization accelerated in the 1960s with 's creation of the around 1963–1964, building on prior BCD schemes to incorporate zoned formats for alphanumeric data. The family, announced in 1964, embedded BCD support in its architecture to ensure compatibility with legacy equipment, solidifying its role in commercial . Although BCD waned in general-purpose personal from the onward, supplanted by pure binary for greater efficiency, it endured in financial and mainframe environments due to its precision in decimal operations, preventing errors in monetary computations within COBOL-based systems that process vast transaction volumes.

Primary Encodings

Packed BCD

Packed binary-coded (PBCD), also known as packed BCD, encodes numbers by storing two digits per 8-bit byte, with the high-order (bits 7–4) representing the tens digit and the low-order (bits 3–0) representing the units digit. Each uses a 4-bit binary value from 0000 (0) to 1001 (9) to directly correspond to the digit it encodes. This format optimizes storage compared to unpacked BCD by halving the space for digit representation, though it requires conversion for character-based . In fixed-point packed decimal, numbers are represented as pure integers without an embedded point, allowing straightforward scaling by powers of 10 for fractional values during computation. Storage allocates full bytes for even-length digit sequences, while odd-length sequences use the high of the final byte for the last digit, leaving the low for the . The overall length in bytes is calculated as (d+1)/2\lceil (d + 1)/2 \rceil, where dd is the number of digits, for the sign nibble. For example, the 1234 (four digits) is stored in the digit portion as 0x12 0x34 (binary 0001 0010 0011 0100), with the appended in an additional low such as 0x0C for positive in a three-byte field. The sign in packed BCD is typically stored in a dedicated low-order of the final byte, separate from the digits, using specific 4-bit patterns outside the 0–9 range. In IBM's format, (hex C) denotes positive, 1101 (hex D) denotes negative, and 1111 (hex F) indicates unsigned or positive-preferred. The hexadecimal values A–F (1010–1111) are generally unused for digit encoding to avoid ambiguity in BCD validity checks, but in the sign position, values like C, D, and F serve as zone or sign indicators, with others reserved for extensions or error detection in some systems.

Zoned BCD

Zoned binary-coded decimal (ZBCD), also known as zoned decimal, represents each decimal digit using an 8-bit byte, where the low-order (4 bits) encodes the digit value from 0 to 9, and the high-order (4 bits) serves as a zone field typically set to a fixed value for compatibility with standards. This format facilitates direct operations with character-based peripherals, as the bytes correspond to printable digit characters in the respective code pages. In the zoned decimal format, prevalent in systems, the zone nibble is uniformly set to 1111 binary (hexadecimal F) for numeric digits, resulting in byte values from F0 to F9 for digits 0 through 9, respectively. These encodings align with character codes for the digits, enabling seamless integration with text processing. An ASCII variant of zoned decimal employs a zone nibble of 0011 0000 binary (hexadecimal 30, or 48) for each digit, producing byte values such as 30 to 39 hexadecimal for digits 0 through 9; for instance, the digit 5 is encoded as 35 hexadecimal (0011 0101 binary). This matches the standard ASCII codes for numeric characters, supporting compatibility in systems using 7- or 8-bit ASCII environments. Fixed-point zoned decimal representations store integer numeric strings where each digit occupies a full byte with its zone, and the is encoded in the high-order of the least significant (rightmost) byte: hexadecimal F indicates positive, while D indicates negative in , overriding the zone for the final digit. Leading digits retain their standard zones (F in ), ensuring the entire field can be treated as a character string for display or input. Conversion from zoned decimal to packed BCD involves stripping the zone nibbles from each byte to isolate the digit nibbles, then combining pairs of consecutive digit nibbles into single bytes (high-order digit first), with the sign placed in the low-order nibble of the final byte; the result is right-aligned and may require padding if the digit count is odd. The reverse process unpacks bytes into individual digit nibbles, inserts appropriate zone nibbles for each (F in ), and applies the sign to the zone of the last byte. This transformation aligns zoned data, which is I/O-oriented, with the denser packed format used for computation. The following table illustrates EBCDIC zoned decimal encodings for digits 0-9 in unsigned form, along with signed variants in the low-order byte:
Decimal DigitUnsigned Zoned Byte (Hex)Positive Signed (Low-Order, Hex)Negative Signed (Low-Order, Hex)
0F0F0D0
1F1F1D1
2F2F2D2
3F3F3D3
4F4F4D4
5F5F5D5
6F6F6D6
7F7F7D7
8F8F8D8
9F9F9D9

Arithmetic Operations

Addition

Binary-coded (BCD) addition involves processing each digit independently using 4-bit nibbles, ensuring the result remains a valid BCD representation (0-9 per digit) by applying a correction mechanism when the binary sum exceeds 9. The process begins with binary of corresponding nibbles from the two operands, followed by detection and adjustment for invalid sums to maintain accuracy without full binary overflow handling. The detailed steps for adding two BCD digits A and B, including an incoming carry C_in (0 or 1), are as follows: first, compute the temporary sum S_temp = A + B + C_in using binary addition; then, check if S_temp > 9 or if a carry-out occurred during the binary addition; if either condition is true, add 6 (binary 0110) to S_temp to produce the corrected digit S and set the outgoing carry C_out to 1; otherwise, C_out is 0 and S = S_temp. This correction works because adding 6 to a value between 10 and 18 (the possible range for two digits plus carry) adjusts it to the range 16-24, which in binary triggers a carry-out of 1 while leaving the low 4 bits as the correct decimal digit (e.g., 10 + 6 = 16, low 0000 with carry 1). The equation for a single digit can be expressed as: S=(A+B+Cin)+6δ,Cout=A+B+Cin+6δ16S = (A + B + C_{in}) + 6 \cdot \delta, \quad C_{out} = \left\lfloor \frac{A + B + C_{in} + 6 \cdot \delta}{16} \right\rfloor where δ=1\delta = 1 if A+B+Cin>9A + B + C_{in} > 9 or if there was a binary carry-out from the low 4 bits, else δ=0\delta = 0. Consider the example of adding the BCD digits 9 (binary 1001) and 1 (binary 0001) with no incoming carry: the binary sum is 1010 (10 decimal), which exceeds 9, so add 6 (0110) to get 10000 (16 decimal), yielding a corrected low nibble of 0000 (0) and C_out = 1. If this is the units digit in a multi-digit number, the carry propagates to the next higher digit's addition. For multi-digit addition in packed BCD format, where two digits are stored per byte (low for units, high for tens), the process is repeated digit-by-digit from right to left, propagating the carry from each to the next. In systems like early mainframes, this ensures compatibility with decimal-oriented peripherals, though some variants (e.g., certain legacy accounting machines) incorporate end-around carry for specific modes to handle sign propagation in signed BCD representations. The final result maintains the packed structure, with the most significant digit potentially generating an overflow carry if needed.

Subtraction and Multiplication

Subtraction in binary-coded decimal (BCD) is commonly performed using the 10's complement method, which transforms the operation into an by complementing the subtrahend and then applying BCD rules to the minuend. This approach avoids direct borrowing across digits, leveraging the same correction mechanisms as BCD (adding 6 to each if the sum exceeds 9). To compute the 10's complement of a BCD number, first find the 9's complement by subtracting each digit DD from 9 (i.e., 9D9 - D), then add 1 to the result, propagating any carry to higher digits. The subtraction proceeds as follows: (1) obtain the 9's complement of the subtrahend; (2) add 1 to convert it to the 10's complement; (3) add this complement to the minuend using standard BCD addition with per-nibble corrections. If a carry is generated from the most significant digit, discard it to obtain the positive result (end-around carry may apply for the least significant digit in some implementations); absence of carry indicates a negative result, which can be handled by taking the 10's complement of the outcome. For example, consider subtracting 13 from 25 in two-digit . The subtrahend 13 has a 9's complement of 86 (9-1=8, 9-3=6). Adding 1 yields the 10's complement 87. Adding 25 + 87 = 112 (in binary: 0010 0101 + 1000 0111 = 1010 1100, corrected for BCD by adding 0110 to exceeding 9, but the sum illustrates the process). Discarding the carry 1 gives the result 12. An alternative direct method involves subtracting digit-by-digit with borrowing, applying a correction by subtracting 6 from the result if a borrow occurs, to maintain valid BCD encoding. Multiplication in BCD is typically implemented using a shift-and-add analogous to binary , but with partial products generated and accumulated via BCD instead of binary . The multiplicand is shifted left by multiples of one digit position (equivalent to multiplying by powers of 10, implemented as left shifts by 4 bits in packed BCD), and added to the accumulator if the corresponding multiplier digit is non-zero, with BCD corrections applied after each . For with single digits, precomputed lookup tables can store the BCD-encoded products of two digits (0-9 × 0-9), reducing computation to table access and accumulation. Division in BCD operates as the reciprocal of , often using a shift-and-subtract loop: the dividend is repeatedly compared to the shifted , subtracting (via 10's complement addition) when possible and incrementing the digit, akin to but with BCD arithmetic for each step.

Implementations in Systems

Mainframe and IBM Systems

's System/360 architecture, announced in 1964, pioneered native hardware support for binary-coded decimal (BCD) to address the needs of commercial computing, particularly for accurate decimal handling in business applications. The design incorporated instructions for both packed BCD, which stores two digits per byte, and zoned BCD, which uses one byte per digit with zone bits for character integration. This enabled efficient processing of financial data without the rounding errors common in binary floating-point representations. Key instructions included PACK for converting zoned decimal to packed format, UNPACK for the reverse, and arithmetic operations such as ADD DECIMAL (AP) for addition, SUBTRACT DECIMAL (SP) for subtraction, MULTIPLY DECIMAL (MP), and DIVIDE DECIMAL (DP). These instructions operate on fields up to 31 digits plus a , packed into 16 bytes, with the CPU's decimal units performing native BCD addition and subtraction to support languages like . Hardware decimal adder circuits in the directly manipulated BCD digits, ensuring precision for transactional workloads. In mainframes, zoned BCD integrates seamlessly with the , serving as the default representation for numeric character data in files and displays, where each digit occupies the low-order four bits of a byte and the high-order bits encode the zone (typically F for numeric digits). This format facilitated I/O operations and data interchange in early systems. Support for BCD persisted into the series of the 1970s, where instructions like those in System/360 were enhanced for extended addressing, with decimal arithmetic remaining a core feature for compatibility. By the post-2000 z/Architecture era, BCD instructions continued to be fully implemented for , even as binary operations dominated general-purpose computing, allowing legacy banking and financial software to run unchanged on modern hardware. In contemporary systems, BCD usage has declined for new applications but remains vital for precise decimal computations in sectors like banking, where packed BCD ensures exact representation of monetary values in COBOL-based . Subsequent processors, including z15 (2019) with Enhanced Vector Facility, z16 (2022) with Advanced Vector Facility for packed decimals, and z17 (2025) with continued decimal support including decimal floating point packed conversion, further enhance BCD performance for AI-integrated workloads. Modern hybrids include for Java's BigDecimal class, which emulates arbitrary-precision decimals using underlying BCD facilities to match mainframe-native performance. Additionally, the z14 processor introduced the Vector Packed Decimal Facility in 2017, enabling SIMD-style operations on BCD data in 16-byte vector registers to accelerate legacy workloads without code changes.

Microprocessors and Other Computers

Binary-coded decimal (BCD) support in microprocessors and other non-mainframe computers has primarily manifested through specialized instructions for adjusting binary arithmetic results to valid BCD representations, reflecting the need for precise decimal computations in early personal and systems. The microprocessor, introduced in 1978, included the Decimal Adjust After Addition (DAA) and Decimal Adjust After Subtraction (DAS) instructions to facilitate packed BCD operations. These instructions operate on the AL register, assuming two unpacked BCD digits (one in the upper and one in the lower ), and correct the result of a prior ADD or SUB instruction by adding or subtracting 6 from the affected if it exceeds 9 or if the auxiliary is set, thereby ensuring the final value remains a valid BCD number. For example, the DAA instruction's is as follows:

if (AL > 9) or (AF == 1) then AL = AL + 6 CF = (CF or (original_AL > 9)) end if if (AH > 9) or (CF == 1) then AH = AH + 6 CF = 1 end if

if (AL > 9) or (AF == 1) then AL = AL + 6 CF = (CF or (original_AL > 9)) end if if (AH > 9) or (CF == 1) then AH = AH + 6 CF = 1 end if

This adjustment mechanism updates the (CF) and auxiliary carry flag (AF) accordingly, enabling efficient BCD arithmetic without full hardware decimal adders. Similar instructions, such as AAA (ASCII Adjust After Addition) and AAS (ASCII Adjust After Subtraction), extend support to zoned BCD formats using ASCII encoding. In extensions to the x86 , AMD64 maintains compatibility with these BCD instructions but restricts their use to 16-bit and 32-bit modes, excluding them from 64-bit due to performance overhead and the dominance of binary arithmetic in modern computing. architectures, designed as reduced instruction set computing (RISC) processors, do not include dedicated hardware BCD operations as standard features; any BCD handling is implemented via software routines, though some vendor-specific extensions or interfaces may offer optional decimal support in embedded contexts. Historical minicomputers like the DEC PDP-11 provided limited BCD support through software libraries for decimal arithmetic, relying on binary instructions for core operations. In contrast, the DEC VAX , evolving from the PDP-11 in the late , incorporated native instructions for decimal string operations, including packed BCD formats compatible with zoned encodings, such as MOVTC for character translation and addition/subtraction on variable-length decimal strings. These VAX instructions treated BCD data as numeric strings, supporting up to 31 digits with sign, and were optimized for business applications requiring exact precision. Burroughs Corporation's medium and large systems from the 1950s through the 1980s, such as the B5000 (1959) and B6700 (1971), were designed with native BCD arithmetic units using a to execute efficiently. These machines performed serial, character-at-a-time decimal operations on BCD-encoded data, storing numbers as alphanumeric strings in memory with each digit occupying six bits (including a zone bit), and utilized a for operand handling without general-purpose registers. This approach minimized conversion overhead for decimal I/O and arithmetic, making Burroughs systems particularly suited for financial and accounting tasks during that era. In contemporary systems lacking hardware BCD support, software emulations prevail, such as Python's module, which implements arbitrary-precision arithmetic using BCD-like internal representations to avoid floating-point rounding errors in financial calculations. Field-programmable gate arrays (FPGAs) also enable custom BCD implementations, where designers replicate adders and adjusters in hardware for specialized applications like emulation or high-speed . The overhead of BCD operations—typically 2-3 times slower than binary due to adjustment steps and larger data widths—has led to sparse hardware support in post-1990s RISC and CISC processors, favoring software libraries for needs in general-purpose .

Hardware and Electronics Usage

Digital Circuits for BCD

Binary-coded decimal (BCD) digital circuits are designed to perform arithmetic operations on decimal digits represented in binary form, ensuring that each 4-bit nibble corresponds to a valid decimal value from 0 to 9. These circuits are essential in hardware implementations where decimal accuracy is paramount, such as in financial systems and calculators. A fundamental component is the BCD , which adds two BCD digits along with a possible carry-in, producing a BCD sum and carry-out. The design incorporates correction logic to handle cases where the binary sum exceeds 9, preventing invalid BCD representations. The BCD adder circuit typically employs a full structure augmented with correction logic implemented using AND for detecting invalid sums and a (MUX) for adding 6 (binary 0110) when necessary. Specifically, the detection logic identifies conditions where the intermediate binary sum is greater than 9 or generates an auxiliary carry, triggering the addition of 6 to adjust the result back to a valid BCD range. This correction ensures decimal integrity without altering the underlying binary arithmetic hardware. The logic uses to compute a correction signal, often defined as K = S3·S2 + S3·S1 + C4, where S3–S0 are the bits of the initial sum and C4 is the carry from the first addition stage. At the gate level, a 4-bit BCD adder is constructed using two 4-bit binary adders in series. The first binary adder computes the initial sum of the two 4-bit BCD inputs (A3–A0 and B3–B0) plus a carry-in, yielding a 4-bit sum (S3–S0) and an auxiliary carry (C4). If the correction signal K is active (indicating S > 9 or C4 = 1), the second binary adder adds 0110 to this sum, producing the final BCD outputs (final S3–S0) and the overall carry-out. This serial arrangement leverages standard binary full adders, minimizing custom logic while introducing a small delay for correction. The carry-out from the second adder serves as the decimal carry to the next digit. For multi-digit BCD addition, carry is managed through chainable designs analogous to binary adders but adapted for correction at each stage. Ripple-carry BCD adders connect the carry-out of one 4-bit stage to the carry-in of the next, propagating the decimal carry sequentially; this is simple but incurs cumulative delays proportional to the number of digits. In contrast, carry-lookahead BCD adders (CLA) precompute generate and propagate signals across digits, incorporating adjustment logic to reduce delay, making them suitable for high-speed applications despite increased complexity. These adaptations ensure efficient handling of carries in contexts, with CLA variants offering logarithmic delay scaling for longer operands. An example for a single-digit 4-bit BCD takes inputs A3–A0 and B3–B0 (each representing digits 0–9), along with a carry-in (Cin). The first 4-bit binary outputs temporary sum bits T3–T0 and auxiliary carry Caux. The correction logic then evaluates if (T3–T0 > 1001 binary or Caux = 1), activating the MUX to select either 0000 or 0110 for addition in the second 4-bit binary , which produces final sum bits S3–S0 and carry-out Cout. This design ensures the output S3–S0 is a valid BCD digit, with Cout indicating a carry of 1. Synchronous BCD counters, used for decimal counting in applications like timers and displays, consist of four flip-flops (JK or D types) with outputs Q3 Q2 Q1 Q0 (Q0 as the lowest significant bit). All flip-flops share a single clock input (CP) for synchronous operation. Combinational logic using AND, OR, and NOT gates connects to the flip-flop inputs (J/K or D) to compute the next state, advancing the count from 0000 to 1001 before generating a carry-out signal (CO) and resetting to 0000 on the subsequent clock edge. BCD circuits have been integrated into arithmetic logic units (ALUs) of early microprocessors to support decimal operations. For instance, the , released in 1971, featured a 4-bit ALU with a Decimal Adjust Accumulator (DAA) instruction that implemented BCD correction logic post-binary , enabling efficient decimal arithmetic in calculator applications. This hardware support for BCD adjustment was crucial for the chip's target use in Busicom's decimal-based systems. Due to the additional correction logic and serial adder stages, BCD circuits exhibit higher latency and power consumption compared to pure binary counterparts.

Displays and Peripherals

Binary-coded decimal (BCD) plays a crucial role in interfacing digital systems with output devices that require direct , particularly in visual displays and input peripherals. One prominent application is in seven-segment displays, where BCD-to-seven-segment decoder chips convert 4-bit BCD codes into signals that activate the appropriate LED or LCD segments to form decimal digits. The SN54LS47, a low-power Schottky TTL , exemplifies this by accepting BCD inputs on pins A-D and driving common-anode seven-segment displays via active-low outputs on pins a-g, ensuring efficient segment illumination without binary-to-decimal conversion overhead. The conversion logic maps each BCD digit from 0000 () to 1001 (9) to a unique combination of the seven segments (labeled a through g), with invalid BCD codes (1010 to 1111) typically blanking the display to prevent erroneous symbols. For instance, BCD 0000 activates segments a, b, c, d, e, and f while deactivating g to display ''. The following table illustrates the output states for digits 0-9, where 0 indicates an active (lit) segment and 1 indicates inactive:
BCD InputabcdefgDigit
00000000001
000110011111
001000100102
001100001103
010010011004
010101001005
011001000006
011100011117
100000000008
100100001009
This mapping, derived from standard decoder designs, ensures precise decimal visualization in devices like digital clocks and meters. In input peripherals, BCD encoding facilitates accurate decimal data entry, as seen in punch card systems using Hollerith code for 80-column cards with 12 punch rows per column. Decimal digits 0-9 are encoded by punching the corresponding row (0 through 9), forming a direct BCD representation that allows mechanical or optical readers to interpret numeric data without complex decoding. Zone punches in rows 11 and 12 extend this for alphanumeric use, but pure numeric fields rely on the 10-row BCD subset for reliable tabulation in early data processing. Early handheld calculators leveraged BCD for both internal arithmetic and display accuracy to avoid floating-point rounding errors in decimal results. The , introduced in 1972, processed 14-digit BCD words in a bit-serial manner, enabling precise trigonometric and exponential functions to be shown directly on its seven-segment without binary conversion artifacts. Similarly, ' early models, such as those using the TMS0100 chipset from the early 1970s, represented numbers as BCD with four bits per digit, supporting accurate decimal output on LED panels in devices like the TI SR-10. BCD extends to other peripherals like printers and terminals, where it ensures decimal output fidelity by delivering digit-by-digit codes to print heads or screens, minimizing errors in financial or scientific printouts. For example, legacy line printers interfaced via BCD signals to drive solenoid-actuated typebars for each digit, providing straightforward conversion to printed numerals. In terminals, BCD inputs to display drivers maintained exact decimal rendering, as in systems requiring isolated BCD outputs for serial-to-decimal translation. In modern embedded systems, BCD interfaces persist in LCD and LED drivers for applications demanding decimal precision, such as industrial panels and automotive dashboards. Chips like the CD4511 CMOS BCD-to-seven-segment decoder continue to be integrated for low-power operation, accepting BCD inputs to control multiplexed displays in microcontrollers, ensuring compatibility with legacy decimal protocols while supporting energy-efficient designs.

Comparison to Binary

Advantages

Binary-coded decimal (BCD) provides precise representation of numbers, avoiding the rounding errors common in binary floating-point arithmetic. Unlike binary floating-point, where fractions such as 0.1 lack an exact binary counterpart and lead to approximations (e.g., 0.1 + 0.2 yielding approximately 0.30000000000000004 instead of exactly 0.3), BCD encodes each digit in a four-bit binary group, ensuring exact storage and computation of values. This precision is essential in domains requiring accurate handling, such as financial systems, where even slight discrepancies can accumulate and affect outcomes. The direct correspondence between BCD nibbles and decimal digits enhances human readability and simplifies input/output processes. In applications like financial software, this mapping allows developers and users to inspect and debug numeric data intuitively, as each four-bit segment translates straightforwardly to a single decimal digit without needing binary-to-decimal conversion routines. This feature streamlines , reporting, and verification tasks. BCD facilitates seamless compatibility with decimal-oriented peripherals and hardware, including calculators, digital meters, and seven-segment displays. By aligning naturally with devices engineered for base-10 output, BCD reduces the of , eliminating the need for additional logic and enabling efficient data exchange in embedded and legacy systems. The six unused codes ( 10–15, or A–F) in each four-bit BCD enable built-in error detection mechanisms. These spare combinations can be designated for parity checks or to indicate invalid digits, allowing systems to detect transmission errors or reliably without extra overhead. For exact decimal computations, BCD offers benefits in scenarios like financial calculations, where operations involving factors of ten (e.g., scaling or alignment) are simpler and avoid the conversion penalties of binary formats. Although storing a number like 999 consumes 12 bits in BCD (four bits per digit) versus 10 bits in pure binary, this trade-off ensures no precision loss from decimal approximations, making BCD preferable for applications prioritizing accuracy over .

Disadvantages

Binary-coded decimal (BCD) representations require four bits to encode each digit from 0 to 9, resulting in a storage overhead compared to pure binary encoding, where approximately 3.32 bits are needed on average per decimal digit due to log2(10)3.32\log_2(10) \approx 3.32. For instance, a 10-digit decimal number occupies 40 bits in standard BCD but only 34 bits in binary (calculated as 10×log2(10)=34\lceil 10 \times \log_2(10) \rceil = 34), leading to up to 20.4% more storage space for BCD in large datasets. This inefficiency arises because BCD dedicates full 4-bit nybbles even though only 10 of the 16 possible combinations are used, wasting capacity for values 10 through 15. Arithmetic operations in BCD are slower than in binary due to the need for correction steps after initial or to ensure valid digits. For example, if the sum of two BCD digits exceeds 9, an adjustment (typically adding 6) is required to correct the result and generate a carry, adding complexity and latency to each operation. Hardware implementations of BCD arithmetic units, such as ALUs, demand additional circuitry for these adjustments, increasing count and elevating power consumption relative to binary counterparts. The fixed 4-bit structure of standard BCD inherently limits its range to decimal digits per nybble, providing no native support for higher-radix operations or non-decimal values without custom extensions or conversions, which further complicates design. In modern computing, BCD has become largely legacy because binary integer and floating-point formats suffice for most non-financial applications, offering superior density, speed, and hardware optimization without the decimal precision pitfalls that BCD addresses only in niche scenarios.

Representational Variations

Signed BCD Formats

Signed binary-coded decimal (BCD) formats extend unsigned BCD representations to handle positive, negative, and zero values by incorporating sign information, typically using either a dedicated sign nibble or overpunching the sign into the representation of the least significant digit. These methods are prevalent in legacy systems like IBM mainframes, where decimal accuracy is critical for applications such as financial computing. In packed BCD, also known as packed decimal format in systems, the is stored in the high-order of the low-order byte, allowing the remaining nibbles to represent the digits. The standard codes are hexadecimal C (binary 1100) for positive values, D () for negative values, and F () for unsigned values. For example, the positive number +123 is encoded as two bytes: 0x12 3C, where the low-order byte combines the digit 3 (0011) with the positive C (1100). The negative counterpart -123 uses 0x12 3D, substituting the negative D. This -magnitude approach keeps the digit values unchanged for the absolute magnitude while isolating the , facilitating straightforward arithmetic operations after adjustment. Zoned BCD formats, common in EBCDIC-encoded data on IBM platforms, allocate a full byte per decimal digit, with the high-order nibble (zone) typically set to F (1111) for unsigned digits 0-9 (resulting in codes F0 to F9). For signed values, the zone nibble of the least significant digit is overpunched to indicate the sign, using C (1100) for positive and D (1101) for negative, while preserving the low-order digit nibble. For instance, +123 in zoned EBCDIC appears as F1 F2 C3, and -123 as F1 F2 D3. Alternative positive signs like A, E, or F and negative signs like B may appear in non-preferred formats, but IBM's NUMPROC(PFD) option standardizes to C, D, and F for consistency. This overpunch method embeds the sign directly into the printable character representation, aiding legacy data interchange. Beyond sign-magnitude representations, some BCD systems employ 10's complement for negative values, where the sign is not stored separately but instead each digit of the magnitude is subtracted from 9 (9's complement) and then 1 is added to the least significant digit, effectively using the full field for the complemented value. This approach, analogous to in binary, simplifies by treating it as but is less common in storage formats like IBM's, which favor sign-magnitude for direct decimal readability. In financial BCD applications, zero handling distinguishes +0 (e.g., C0 in zoned or with positive sign in packed) from -0 (D0 or negative sign), preserving debit/credit semantics even for null balances in ledgers.

Telephony BCD (TBCD)

Telephony BCD (TBCD) is a packed binary-coded decimal encoding scheme optimized for representing telephone numbers and addresses in mobile telecommunications protocols, particularly within the and subsequent standards. Defined as an OCTET STRING in notation for the , it supports digits 0-9 along with telephony-specific characters *, #, a, b, and c, using a filler character F for padding. This format emerged in the 1990s as part of GSM specifications to efficiently transmit numeric addressing data over limited bandwidth links. The structure of TBCD encodes two decimal digits per octet, with the high-order nibble holding the more significant digit and the low-order nibble the less significant one. Digits are packed starting from the most significant digit in the high-order nibble of the first octet, the next digit in the low-order nibble of the first octet, and so on, up to the least significant digit in the low-order nibble of the last octet (for even length) or high-order nibble (for odd length, with low-order nibble set to F). Each digit 0-9 is directly mapped to its hexadecimal equivalent (0x0 to 0x9), while * maps to 0xA, # to 0xB, a to 0xC, b to 0xD, c to 0xE, and the filler to 0xF. When the total number of digits is odd, the unused low-order nibble in the final octet is filled with 0xF. In address fields, leading zeros are omitted unless part of the number. In SMS protocols, TBCD encodes originator and destination addresses within the Transfer Protocol Data Unit (TPDU) as outlined in GSM 03.40. The address field begins with a one-octet length indicator (number of semi-octets for the address value, i.e., the number of digits), followed by a type octet combining Type of Number (TON) and Numbering Plan Identification (NPI), and then the TBCD-packed address value. For an international number like +1234567890 (digits 1234567890), TON=001 (international) and NPI=0001 (E.164/ISDN) yield a type octet of 0x91, with the address value packed as 0x12 0x34 0x56 0x78 0x90. The filler 0xF ensures even nibble alignment for odd-length addresses, such as +123456789 (digits 123456789) becoming length 0x09, type 0x91, followed by 0x12 0x34 0x56 0x78 0x9F. This semi-octet packing allows up to 20 digits in 10 octets, balancing density and protocol efficiency. TBCD differs from standard BCD by omitting zone bits or indicators, focusing solely on unsigned numeric and special character representation for addressing purposes. It employs a consistent two-digits-per-octet scheme without variable , enabling fixed in protocol stacks; for instance, an octet pair accommodates exactly four digits, streamlining data handling compared to zoned formats. and NPI precede the digits to denote context like international or national numbering, absent in general BCD. Conversion from ASCII or string to TBCD involves extracting digits, mapping each to its 4-bit value, and interleaving into octets with high/low assignment starting from the most significant digit. Special handling for /NPI sets the type octet—e.g., 0x91 for international —before appending the packed value; decoding reverses the process, extracting nibbles from high to low per octet to reconstruct digits from most to least significant while ignoring fillers. This mapping ensures compatibility with legacy equipment. TBCD's use expanded in post-2000 releases for operations in and beyond, appearing in specifications like TS 29.002 for signaling messages such as location updates and routing. While integral to legacy / interfaces, it sees partial replacement by UCS-2 or in modern IP-based over IMS to support international characters, though TBCD persists in core network for .

Applications

Financial Computing

Binary-coded decimal (BCD) plays a critical role in financial computing by enabling exact representation and manipulation of numbers, particularly in handling values where precision to the cent or smaller units is mandatory. In banking and systems, binary floating-point formats can introduce errors—for instance, repeated additions of 0.10 may not yield exactly 1.00 due to base-2 approximations—whereas BCD stores each digit in a 4-bit , preserving exactness without drift. This precision is essential for applications like calculations and balance updates, preventing cumulative discrepancies that could lead to regulatory non-compliance or financial losses. Standards such as those governing arithmetic in financial systems, including the SQL , often leverage BCD implementations to ensure and accuracy in data storage and exchange. In , for example, columns are stored using packed BCD format, where two digits occupy one byte plus a sign , supporting up to 31 digits of precision for financial records. , a staple in legacy financial software, integrates BCD through the COMP-3 (packed decimal) usage in PICTURE descriptions, allowing programmers to define fields like PIC 9(9)V99 COMP-3 for exact storage of amounts up to nine integer digits and two places, facilitating reliable arithmetic operations in . Practical examples include mainframe-based banking systems where BCD formats process transaction amounts without conversion losses, as seen in environments handling high-volume financial data. Modern languages persist this approach through decimal types for arbitrary precision: Java's BigDecimal uses an array-based representation of digits, ideal for financial APIs and compliance-driven calculations, while .NET's System.Decimal employs a 128-bit structure supporting 28-29 significant digits with base-10 scaling, explicitly recommended for monetary computations to avoid floating-point pitfalls.

Telecommunications and Legacy Systems

In telecommunications protocols, binary-coded decimal (BCD) ensures precise encoding of decimal digits for phone numbers and billing information. BCD (TBCD), an extension of BCD tailored for , is applied in the Signaling System No. 7 (SS7) protocol, where each digit in the called party number within the Initial Address Message is represented by 4-bit BCD codes to facilitate call setup and routing. In the Global System for Mobile Communications (), TBCD encodes calling and called party numbers in Call Detail Records (CDRs) for billing and charging, as defined in mediation system specifications for offline processing of usage data. The Integrated Services Digital Network (ISDN) also relies on BCD for signaling, with the ITU-T Q.931 standard using a semi-octet BCD format to encode calling and called party numbers, where each digit occupies 4 bits alongside indicators for number type and plan identification. This approach supports basic call control by maintaining compatibility with decimal-based telephony addressing. BCD endures in legacy systems due to its decimal accuracy in environments requiring exact numeric handling. IBM mainframes running MVS and OS/390 (precursors to z/OS) extensively use packed decimal, a compact BCD variant, for storing and processing numeric data such as transaction amounts and dates in telecommunications and enterprise applications. The Year 2000 (Y2K) issue exposed vulnerabilities in these BCD-based date fields, prompting fixes like expanding BCD representations to support four-digit years while preserving legacy record layouts in mainframe software. In point-of-sale (POS) terminals and automated teller machines (ATMs), the standard governs transaction messaging and utilizes packed BCD for key fields like amounts, encoding two digits per byte to optimize bandwidth and avoid floating-point precision errors in calculations. This format persists in legacy payment infrastructures interfacing with mainframes for and settlement. Migration challenges from BCD-based systems remain in sectors like , where mainframes continue to rely on packed decimal for high-volume , complicating transitions to binary formats due to compatibility and precision requirements.

Alternative Encodings

Higher-Density BCD Variants

Standard binary-coded decimal (BCD) representations allocate 4 bits per decimal digit, yielding a density of 4 bits per digit (bpd), which exceeds the theoretical minimum of log2103.32\log_2 10 \approx 3.32 bpd needed to encode decimal information in binary without loss. Higher-density BCD variants optimize this by compressing multiple digits into fewer bits using fixed or variable-length codes, aiming to approach the information-theoretic limit while preserving the decimal structure for compatibility with existing BCD systems. These approaches typically involve trade-offs, such as increased computational overhead for encoding and decoding, and challenges in performing arithmetic directly on the compressed form without full expansion. The Chen-Ho encoding, developed by T. C. Chen and I. T. Ho in , represents a foundational higher-density variant that packs three digits into 10 bits, achieving an effective density of 3.333 bpd with minimal wastage of 0.34% relative to the maximum possible combinations. This fixed-length scheme employs a combinatorial mapping akin to a for digit triples, where the three 4-bit BCD digits are rearranged (often by sorting or permuting) and adjusted using 2 additional bits to uniquely represent all 1,000 possible three-digit combinations within the 1,024 available 10-bit values. For instance, common low-value digits benefit from efficient bit allocation in the mapping, allowing subsets like 000 to map directly to all-zero bits. However, the non-uniform bit distribution across digit groups introduces decoding overhead, as reverse mapping requires checking permutations to recover the original order. Other higher-density variants include biased BCD schemes, which shift the standard 4-bit codes (e.g., adding a like 3 in BCD) to facilitate compression in specific contexts, such as easing carry propagation or enabling better packing in variable scenarios, though they generally maintain close to 4 bpd unless combined with multi-digit grouping. Additionally, 10-bit-per-3-digit schemes, building on Chen-Ho principles, have been explored for further optimization, such as in patents extending for variable-length extensions where groups of N digits use proportionally fewer bits. An illustrative example of a variable-length extension inspired by these methods might encode frequent digits with shorter codes—e.g., digit 1 as 01 (2 bits), 2 as 10 (2 bits), and 3 as 11 (2 bits)—yielding 6 bits total for the number 123, averaging below 3.32 bpd for digit streams dominated by low values using a prefix-free . Arithmetic operations on higher-density BCD encodings pose significant challenges due to non-uniform lengths or mappings, often necessitating alignment of digit groups, partial decoding during or , and handling carry across compressed boundaries, which can increase latency compared to standard BCD in hardware implementations. Despite these complexities, such variants remain rare in practice, primarily confined to academic research and specialized proprietary systems for financial data compression where storage savings justify the overhead.

Non-BCD Decimal Methods

The IEEE 754-2008 standard defines decimal floating-point formats that store decimal numbers in binary form while preserving exact decimal precision, serving as a modern alternative to traditional BCD for applications needing decimal fidelity without binary rounding errors. These formats include decimal32, which uses 32 bits to encode up to 7 decimal digits in the with an exponent range of -95 to +96, and decimal64, which employs 64 bits for up to 16 decimal digits with an exponent range of -383 to +384. Unlike BCD, which allocates fixed 4 bits per digit, these formats use variable-density encoding for the combined with a biased exponent and , enabling compact representation of decimal values in binary hardware. Two primary encodings for the significand in these formats are Binary Integer Decimal (BID) and Densely Packed Decimal (DPD). BID, developed by , represents the significand as a single binary integer equivalent to the decimal value, padded to full precision with leading zeros if necessary, and includes a short "cohort" field to specify the actual number of digits for shorter values, improving density. For instance, the decimal number 123 in BID (assuming a format supporting at least 3 digits, like a subset of decimal32) has a significand of 01111011 (the 8-bit binary for 123), with the cohort encoding indicating 3 digits to avoid trailing zeros in interpretation. DPD, designed by , compresses groups of three digits into 10 bits using a nonlinear mapping that ensures all valid BCD combinations are representable, facilitating efficient conversion between decimal strings and packed storage. BID and DPD offer trade-offs in performance: BID supports faster arithmetic operations by directly utilizing binary integer hardware for and , though it requires conversion for decimal input/output, while DPD excels in decimal-to-binary conversions but demands specialized logic for arithmetic, making it preferable for systems with frequent human-readable interfaces. Both maintain decimal-exact results for operations like and , addressing BCD's inefficiencies in scaling, and are implemented in software libraries for precise decimal , such as those in financial and scientific applications. Additional non-BCD decimal methods include variants for decimal digits, which assign binary codes to 0-9 such that successive digits differ by exactly one bit, minimizing transition errors in electromechanical devices like rotary dials or shaft encoders. Unary decimal encoding represents digits 0-9 with 1 to 10 asserted bits (e.g., 0000000000 for 0, 1111111111 for 9), useful only for tiny ranges in specialized counters due to its extreme space inefficiency. Historically, encoding provided a simple decimal alternative by adding 3 (binary 0011) to each standard 4-bit digit code, yielding self-complementing representations (e.g., 0 becomes 0011, 9 becomes 1100) that simplify 9's complement subtraction without full BCD addition circuitry, and was employed in calculators and early computers for arithmetic ease.

References

Add your contribution
Related Hubs
User Avatar
No comments yet.