Understanding Packed BCD
See also Understanding
Packed BCD (Binary Coded Decimal) is a numeric format that was
directly supported on cpu's almost from the beginning, and still is
today. Simply put, it relies on the fact that 4 bits are more than
sufficient to represent decimal numbers. Therefore, two decimal
numbers can be held in each byte, a 32 bit register can hold 8 such
numbers, and a 64 bit register can of course hold 16. Many cpu's
can do BCD math - it's just a matter of having the half bytes carry
when their value exceeds 9, conceptually not a lot different than
ordinary binary math. It also isn't very hard to write programs to
do math on BCD numbers of arbitrary length.
There is also unpacked BCD, which of course is very wasteful of
space: 1 byte per numeric digit stored.
If you look at hex representations of BCD numbers, the
individual digits are simply read left to right: what you see is
what you have (ignoring sign and any exponent). BCD formats are
directly human readable without any more math than translating the
bit values to numbers.
The advantage of BCD over floating point formats is that numbers
can be accurately represented (assuming you have enough bytes to
store the number). Floating point is a compromise: some numbers
(6.25) can be represented accurately, but most can only be
approximated. The approximation is very close with double precision
formats, but it is still an approximation.
The disadvantage is range. In 32 bits, IEEE floating point can
store numbers in the range of 2^-126 to 2^127
- very large numbers. In the same 32 bits, even if you ignore the
need to store a sign, the largest possible number in packed BCD
would be 99999999. That's less than 2^27 right there,
which is a long, long way from IEEE floating point range. As you
also need the sign and an exponent to locate the decimal point,
packed BCD obviously needs much more storage space to handle
typical numbers. However, people have used this: MBASIC on Tandy
Xenix used packed BCD for floating point, and many an accounting
package used BCD internally to avoid rounding errors.
More Articles by Tony Lawrence
Find me on Google+
© 2010-10-29 Tony Lawrence