A simple implementation

...The low_performance approach

Basically, BCD arithmetic works in two steps:
First, the ALU performs a binary A+B or A-B.
Second, we need some circuitry, to determine,
if we have to add/subtract 6 for correcting the result.

For decimal A+B: BCD_ADD = 1.
C_IN is the (high active) carry from the next lower digit.
For a result that doesn't fit into 4 Bit (> decimal 15),
the ALU forces C_OUT to 1, incrementing the next higher digit.
And as a correction, we have to add 6 to the result.
With results from (decimal) 10..15, we have either
Q3=1 AND Q2=1, or Q3=1 AND Q1=1... or both.
In that case, we also need to add 6 and to set C_OUT active.

For decimal A-B: BCD_SUB = 1.
C_IN works as a low_active borrow, means that C_IN = 0 whould set Q to A-B-1.
For results < 0, like 8-9, C_OUT will be 0 (active),
we have to subtract 6 from the result, and to decrement the next higher digit.

When BCD_ADD = 0 and BCD_SUB = 0, the BCD correction is turned off,
and the ALU will work in binary mode as usual.

That's all.


A lot of older CPU designs have to do BCD arithmetic in two steps:
First a normal binary add/sub, that writes the result into the accumulator.
Second a decimal correction, what means OpCodes like DAA/DAS.

Basically, it works as described above, except that we may have more than
one digit (4 Bits) as CPU data_word length.

Examples: 8080/8085, Z80, 80X86, 6802/6809/68HC11, the 8031 family, PIC, etc.

The 68000 and it's successors (like 68332) have special opcodes like
ABCD (add BCD)
SBCD (subtract BCD)
for decimal arithmetic.

The 6502 features a D_Flag inside the status_register.
(Decimal_Flag, set/cleared with SED/CLD.)
When active, the CPU does ADC/SBC in decimal arithmetic.
Else, it adds/subtracts in binary (hexadecimal).
Needless to say, that the operating system of a 6502 based computer
may act confused/unpredictable, when forgetting to clear that flag.

Newer RISC processors don't seem to have any hardware_support for decimal arithmetic.
In fact, BCD arithmetic doesn't seem to be used often with modern software.


[HOME] [UP]/ [BACK] [1] [2] [3] [4] [5] [6] [7] [NEXT]

(c) Dieter Mueller 2006