Binary coded decimal

From Rosetta Code
Revision as of 01:25, 12 July 2022 by Puppydrum64 (talk | contribs) (Created page with "{{draft task}} Binary-Coded Decimal (or BCD for short) is a method of representing decimal numbers by storing what appears to be a decimal number...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Binary coded decimal is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Binary-Coded Decimal (or BCD for short) is a method of representing decimal numbers by storing what appears to be a decimal number but is actually stored as hexadecimal. Many CISC CPUs (e.g. X86 Assembly have special hardware routines for displaying these kinds of numbers.) On low-level hardware, such as 7-segment displays, binary-coded decimal is very important for outputting data in a format the end user can understand.

Task

Use your language's built-in BCD functions, OR create your own conversion function, that converts an addition of hexadecimal numbers to binary-coded decimal. You should get the following results with these test cases:

  •   0x19 + 1 = 0x20
  •   0x30 - 1 = 0x29
  •   0x99 + 1 = 0x100
Bonus Points

Demonstrate the above test cases in both "packed BCD" (two digits per byte) and "unpacked BCD" (one digit per byte).



=={{header

Z80 Assembly

The DAA function will convert an 8-bit hexadecimal value to BCD after an addition or subtraction is performed. The algorithm used is actually quite complex, but the Z80's dedicated hardware for it makes it all happen in 4 clock cycles, tied with the fastest instructions the CPU can perform.

<lang z80> PrintChar equ &BB5A ;Amstrad CPC kernel's print routine org &1000

ld a,&19 add 1 daa call ShowHex call NewLine

ld a,&30 sub 1 daa call ShowHex call NewLine

ld a,&99 add 1 daa

this rolls over to 00 since DAA only works with the accumulator.
But the carry is set by this operation, so we can work accordingly.

jr nc,continue ;this branch is never taken, it exists to demonstrate the concept of how DAA affects the carry flag. push af ld a,1 call ShowHex pop af continue: call ShowHex call NewLine ret ;return to basic

ShowHex: push af and %11110000 rrca rrca rrca rrca call PrintHexChar pop af and %00001111 ;call PrintHexChar ;execution flows into it naturally. PrintHexChar: ;this little trick converts hexadecimal or BCD to ASCII. or a ;Clear Carry Flag daa add a,&F0 adc a,&40 jp PrintChar</lang>

Output:
20
29
0100